zordius / lightncandy

An extremely fast PHP implementation of handlebars ( http://handlebarsjs.com/ ) and mustache ( http://mustache.github.io/ ),
https://zordius.github.io/HandlebarsCookbook/
MIT License
610 stars 76 forks source link

Fix named references in each helper if variable is string/integer (fix #267) #275

Closed jrenggli closed 6 years ago

jrenggli commented 7 years ago

Tried to fix the issue described in #267. By applying this PR it's possible to use named references. Before it only worked if the value was an array or object. e.g.

{{#each users as |userName userId|}}
  Id: {{userId}} Name: {{userName}}
{{/each}}

This is my first contribution for lightncandy and I'm unsure if this PR fits into the overall architecture or if there's a better place to fix this issue.

dhuf commented 7 years ago

Hi @zordius, any news on that pull-request ? Thanks a lot

zordius commented 6 years ago

Sorry for the long waiting, I will verify the handlebars.js behavior then decide how to deal with this pull request, thanks.

zordius commented 6 years ago

Sorry I can not accept this pull request because it did not really fix the issue. Here is a test case as jsfiddle: http://jsfiddle.net/4Lkmnru6/28/

With your patch , the output is: #0>b|Array#1>d|Array but the expected output should be #a>b|b#c>d|d

The reason: Your patch overwrites the whole context for only block params, so {{.}} can not receive correct value.

zordius commented 6 years ago

Here is the testing code:

<?php

require('./vendor/autoload.php');
use LightnCandy\LightnCandy;

// The Template:
$template = '{{#each . as |v k|}}#{{k}}>{{v}}|{{.}}{{/each}}';

$phpStr = LightnCandy::compile($template, array(
  // Used compile flags
  'flags' => LightnCandy::FLAG_HANDLEBARS,
));

// Input Data:
$data = array(
  'a' => 'b',
  'c' => 'd'
);

// Save the compiled PHP code into a php file
file_put_contents('render.php', '<?php ' . $phpStr . '?>');

// Get the render function from the php file
$renderer = include('render.php');

echo "Result:\n" . $renderer($data) . "\n";
?>