XaminProject / handlebars.php

Handlebars processor for php
331 stars 132 forks source link

'this' does not work with 'each' iterator #5

Closed cmoy closed 11 years ago

cmoy commented 11 years ago

As described on the http://handlebarsjs.com/ website.

<ul class="people_list">
  {{#each people}}
  <li>{{this}}</li>
  {{/each}}
</ul>

when used with this context:

{
  people: [
    "Yehuda Katz",
    "Alan Johnson",
    "Charles Jolley"
  ]
}

will result in:

<ul class="people_list">
  <li>Yehuda Katz</li>
  <li>Alan Johnson</li>
  <li>Charles Jolley</li>
</ul>

Currently it'll iterate through but it does not render the content for {{this}}, instead it is left blank.

cmoy commented 11 years ago

To fix this issue, I created a new array for the {{#each}} helper. I edited the Helpers.php file in the method addDefaultHelpers() lines 90-107 shown below:

        $this->add(
            'each', 
            function ($template, $context, $args, $source) {
                $tmp = $context->get($args);
                $buffer = '';
                if (is_array($tmp) || $tmp instanceof Traversable) {
                    foreach ($tmp as $var) {
                        if(!is_array($var)) {
                            $var = array("this" => $var);
                        }
                        $context->push($var);
                        $buffer .= $template->render($context);
                        $context->pop();
                    }
                }            
                return $buffer;
            }
        ); 
fzerorubigd commented 11 years ago

For doing this, you can use {{.}} and not {{this}}

fzerorubigd commented 11 years ago

You can use this too.