XaminProject / handlebars.php

Handlebars processor for php
331 stars 134 forks source link

Helpers not passed correct this value within each block #49

Closed brianDoherty closed 10 years ago

brianDoherty commented 10 years ago

When trying to pass a helper function an argument inside of an each loop, I get the string this passed as the argument to the helper, rather than the current value of the each loop.

$engine->addHelper('foo', function($template, $context, $arg){
  return new \Handlebars\SafeString( '<strong>' . $arg. '</strong>' );
}); 

echo $engine->render(
  'Planets:<br />{{#each planets}}<h6>{{foo this}}</h6>{{/each}}',
  array(
    'planets' => array(
      'Mercury',
      'Venus',
      'Earth',
      'Mar'
    )   
  )   
);

Outputs:

Planets:<br /><h6><strong>this</strong></h6><h6><strong>this</strong></h6><h6><strong>this</strong></h6><h6><strong>this</strong></h6>

Whereas if I don't call a helper inside of the each loop, I get the correct value:

echo $engine->render(
  'Planets:<br />{{#each planets}}<h6>{{this}}</h6>{{/each}}',
  array(
    'planets' => array(
      'Mercury',
      'Venus',
      'Earth',
      'Mar'
    )   
  )   
);

Outputs:

Planets:<br /><h6>Mercury</h6><h6>Venus</h6><h6>Earth</h6><h6>Mar</h6>

I'm attempting to use the same Handlebar templates server side and client side, and this is preventing me from doing that.

JustBlackBird commented 10 years ago

Your helper is wrong. You need to get value from the context instead of directly use $arg argument.

The code of the helper should looks like the following:

$engine->addHelper('foo', function($template, $context, $arg){
  $value = $context->get($arg);
  return new \Handlebars\SafeString( '<strong>' . $value . '</strong>' );
}); 
everplays commented 10 years ago

Just like @JustBlackBird explained, handlebars.php doesn't parse arguments for you, you need to do it yourself. But there's a helper for it that you can use \Handlebars\Template::parseArguments. For more info please referrer to https://github.com/XaminProject/handlebars.php/pull/37 or checkout testArgumentParser & argumentParserProvider methods in HandlebarsTest.php file.