PageRenderTime 46ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/jQueryTmpl/Element/Each.php

http://github.com/xyu/jquery-tmpl-php
PHP | 66 lines | 47 code | 13 blank | 6 comment | 4 complexity | 15ce504aec4a912486ccdc01dcf9d1e7 MD5 | raw file
  1. <?php
  2. class jQueryTmpl_Element_Each extends jQueryTmpl_Element_TypeBlock implements jQueryTmpl_Element_TypeRenderable
  3. {
  4. private $_firstToken;
  5. private $_elements;
  6. public function parseTokens(array $tokens)
  7. {
  8. // Remove first and last token
  9. $this->_firstToken = array_shift($tokens);
  10. $lastToken = array_pop($tokens);
  11. // Make sure we have the right types of tokens
  12. if (!($this->_firstToken instanceof jQueryTmpl_Token_EachStart && $lastToken instanceof jQueryTmpl_Token_EachEnd))
  13. {
  14. throw new jQueryTmpl_Element_Exception('Token mismatch, cannot create {{each}} element.');
  15. }
  16. $this->_elements = $this->_parser->parse($tokens);
  17. }
  18. public function render()
  19. {
  20. $defaultOptions = array
  21. (
  22. 'index' => '$index',
  23. 'value' => '$value'
  24. );
  25. $options = array_merge($defaultOptions, $this->_firstToken->getOptions());
  26. $blockData = $this->_data->getValueOf($options['name']);
  27. if (!(is_array($blockData) || $blockData instanceof stdClass))
  28. {
  29. // If there is no valid data for this each block it becomes nothing.
  30. return '';
  31. }
  32. $rendered = '';
  33. foreach($blockData as $index => $value)
  34. {
  35. // Make a copy of the data to use as local
  36. $localData = $this->_data;
  37. // Add our local vars to copy of data
  38. $localData
  39. ->addDataPair($options['index'], $index)
  40. ->addDataPair($options['value'], $value)
  41. ->addDataPair('this', $value);
  42. // Now call each element and give them the data as well.
  43. foreach ($this->_elements as $element)
  44. {
  45. $rendered .= $element
  46. ->setData($localData)
  47. ->setCompiledTemplates($this->_compiledTemplates)
  48. ->render();
  49. }
  50. }
  51. return $rendered;
  52. }
  53. }