Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Different behaviour than Javascript when modifying context in helper #350

Open
kohlerdominik opened this issue Jun 24, 2021 · 1 comment

Comments

@kohlerdominik
Copy link

kohlerdominik commented Jun 24, 2021

The PHP Code:

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

// The Template:
$template = <<<VAREND
  Before:               {{var}}                     <br>
  (Setting Variable)    {{setvar "var" "Foo"}}      <br>
  After:                {{var}}
VAREND;

// Helpers:
$helpers = [
    'setvar' => function ($name, $value, &$options) {
        $options['data']['root'][$name] = $value;
    },
];

$phpStr = LightnCandy::compile($template, array(
    // Used compile flags
    'flags' => LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_HANDLEBARSJS,
    'helpers' => $helpers,
));

echo "Generated PHP Code:\n$phpStr\n";

// Input Data:
$data = array(
    'var' => 'value'
);

// 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);
echo "\n";

Result with Lightncandy:

Before: value
(Setting Variable)
After: value

Result with handlebars.js (JSFiddle)

Before: value
(Setting Variable)
After: Foo 

The Issue:

In aboves example we see, that in handlebars.js it possible to modify the context by simply assigning a new value to the context offset. But this seems not to work the same way with Lightncandy.

Is there a different way to modify the context?

@duzun
Copy link

duzun commented May 17, 2022

Here is what I found works:

// Helpers:
$helpers = [
    'setvar' => function ($name, $value, &$options) {
        $options['_this'][$name] = $value;
    },
];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants