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
608 stars 76 forks source link

Custom Block Helper with blockParams #360

Open toovy opened 2 years ago

toovy commented 2 years ago

Hi!

I'd like to use block parameters in my own helper. In my example scenario I want to add two values and "store" them as block variable "result" with a "let" helper (inspired by the ember.js let helper https://guides.emberjs.com/release/components/helper-functions/#toc_the-let-helper). Looking at the handlebars "with"-helper (https://github.com/handlebars-lang/handlebars.js/blob/master/lib/handlebars/helpers/with.js) I tried to create the following code where I expect result to be 3.

In my case this fails, but I can't figure out how blockParams works exactly and I could not find any lightncandy docs for it. I know that I could switch the context and just use {{.}}, but I hate the context switching feature and want to explicitely name the new I looked at the docs here https://zordius.github.io/HandlebarsCookbook/0022-blockhelper.html and here https://zordius.github.io/HandlebarsCookbook/9002-helperoptions.html .

Any help would be appreciated. Thanks!

$template = <<<EOF
{{#let (add 1 2) as |result|}}
  Result is: {{result}}
{{/let}}
EOF;

$phpStr = LightnCandy::compile($template, [
  'flags' => LightnCandy::FLAG_HANDLEBARS,
  'helpers' => [
    "add" => function ($a, $b) {
      return $a + $b;
    },
    'let' => function ($context, $options) {
      return $options['fn']($context, [
        "data" => $options['data'],
        "blockParams" => [$context]
      ]);
    }
  ]
]);