Posted By

adamcbrewer on 02/18/11


Tagged

php html helpers


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

adamcbrewer


HTML Helper


 / Published in: PHP
 

This is a custom HTML helper class based on CakePHP's built-in helper class, designed for constructing neater, well-formatted links.

There are plans to extend this further.

  1. <?php
  2.  
  3. /**
  4.  *
  5.  * HTML helper class for the following:
  6.  *
  7.  * HTML anchor tags with mailto's
  8.  *
  9.  */
  10. class HtmlHelper {
  11.  
  12. // set the domain for environment
  13. var $domain = 'http://test.com/';
  14.  
  15. /**
  16.   * Generate well-formatted links for scripts, CakePHP style
  17.   *
  18.   *
  19.   */
  20. public function link($name = null, $url = null, $options = array()) {
  21.  
  22. // open the links and set the url, accounting for mailto links
  23. if (!empty($options) && is_array($options) && array_key_exists('type', $options) && $options['type'] == 'mailto') {
  24. $html_link = '<a href=mailto:"'.$url.'"';
  25. } else {
  26. $html_link = '<a href="'.$this->domain.$url.'"';
  27. }
  28.  
  29. // set any other attributes from $options
  30. if (!empty($options) && is_array($options)) {
  31.  
  32. $accepted_options = array('class', 'title', 'id', 'target', 'rel', 'onClick');
  33.  
  34. foreach ($options as $option => $value) {
  35.  
  36. // filter for accepted options
  37. if (in_array($option, $accepted_options)) {
  38.  
  39. // only allow strings
  40. if (!is_array($value)) {
  41.  
  42. $html_link .= ' '.$option.'="'.$value.'"';
  43.  
  44. }
  45.  
  46. }
  47.  
  48. }
  49.  
  50. }
  51.  
  52. // close off the link
  53. $html_link .= '>'.$name.'</a>';
  54.  
  55. return $html_link;
  56.  
  57. }
  58.  
  59. }
  60.  
  61. // for testing purposes only
  62. // $Html = new HtmlHelper;
  63. // echo $Html->link('test', '[email protected]', array('class'=>'some-class', id'=>'the id', 'title'=>'This is the tile', 'rel'=>'the_rel', 'onClick'=>'alert()'));

Report this snippet  

You need to login to post a comment.