Posted By

ping_ch on 02/06/09


Tagged

elements cakephp helper


Versions (?)

Element helper for CakePHP


 / Published in: PHP
 

URL: element-helper

  1. <?php
  2.  
  3. /**
  4.  * Element Helper
  5.  * Helps formatting strings with custom markup
  6.  *
  7.  * @author Stefan Zollinger
  8.  * @license MIT
  9.  * @version 1.0
  10.  */
  11.  
  12. class ElementHelper extends Helper {
  13.  
  14. /**
  15. * The base directory containing your elements.
  16. * Set to '' to include all elements in your views/elements folder
  17. */
  18. var $baseDir = 'templates';
  19.  
  20. /**
  21. * Applies all the formatting defined in this helper
  22. * to $str
  23. * (Currently only $this->getElements() )
  24. *
  25. * @return $str Formatted string
  26. * @param string $str
  27. */
  28. function format($str) {
  29. $str =& $this->getElements($str);
  30. return $str;
  31. }
  32.  
  33. /**
  34. *
  35. * Replaces [element:element_name] tags in a string with
  36. * output from cakephp elements
  37. * Options can be defined as follows:
  38. * [element:element_name id=123 otherVar=var1 nextvar="also with quotes"]
  39. * [e:element_name]
  40. *
  41. * @return formatted string
  42. * @param $str string
  43. */
  44. function getElements(&$str){
  45. $View =& ClassRegistry::getObject('view');
  46. preg_match_all('/\[(element|e):([A-Za-z0-9_\-]*)(.*?)\]/i', $str, $tagMatches);
  47.  
  48. for($i=0; $i < count($tagMatches[1]); $i++){
  49.  
  50. $regex = '/(\S+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))+.)[\'"]?/i';
  51. preg_match_all($regex, $tagMatches[3][$i], $attributes);
  52.  
  53. $element = $tagMatches[2][$i];
  54. $options = array();
  55. for($j=0; $j < count($attributes[0]); $j++){
  56. $options[$attributes[1][$j]] = $attributes[2][$j];
  57. }
  58. $str = str_replace($tagMatches[0][$i], $View->element($this->baseDir.DS.$element,$options), $str);
  59.  
  60.  
  61. }
  62.  
  63. return $str;
  64. }
  65.  
  66. }
  67.  
  68. ?>

Report this snippet  

You need to login to post a comment.