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

fix: Pass input data of current scope to {{else}} of {{#each}} #369

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

eliashaeussler
Copy link

@eliashaeussler eliashaeussler commented Feb 7, 2024

Problem

Given the following Handlebars template:

{{#each paragraphs}}
    <p>{{this}}</p>
{{else}}
    <p class="empty">{{foo}}</p>
{{/each}}

Given the following context:

{
    "foo": "baz"
}

When rendering the template with this context, {{else}} is being rendered because paragraphs is missing in the context. With native handlebars.js, this generates the following result:

<p class="empty">baz</p>

👉 For reference, have a look at the playground on handlebarsjs.com.

However, when rendering the same template and context with lightncandy, the result is:

<p class="empty"></p>

👉 For reference, create and run the following PHP script:

require_once __DIR__ . '/vendor/autoload.php';

$template = <<<HBS
{{#each paragraphs}}
    <p>{{this}}</p>
{{else}}
    <p class="empty">{{foo}}</p>
{{/each}}
HBS;

$compileResult = \LightnCandy\LightnCandy::compile($template, [
    'flags' => \LightnCandy\LightnCandy::FLAG_HANDLEBARS,
]);
$fn = \LightnCandy\LightnCandy::prepare($compileResult);

echo $fn([
    'foo' => 'baz',
]);

And check the output:

$ php test.php
<p class="empty"></p>

Solution

This PR fixes the issue by passing input data of the current scope to the else callback in Runtime::sec(). In addition, a test case is added which covers the above scenario.

@eliashaeussler eliashaeussler changed the title Pass input data of current scope to {{else}} of {{#each}} fix: Pass input data of current scope to {{else}} of {{#each}} Feb 8, 2024
theodorejb added a commit to devtheorem/php-handlebars that referenced this pull request Jan 1, 2025
@theodorejb
Copy link

This is fixed in my Handlebars-focused fork: https://github.com/devtheorem/php-handlebars

@eliashaeussler
Copy link
Author

This is fixed in my Handlebars-focused fork: devtheorem/php-handlebars

@theodorejb Wow, nice! I didn't recognize that you forked the repo and started with improvements. I really like it ❤️ Will check if we can switch https://github.com/CPS-IT/handlebars from this repo here to your fork.

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

Successfully merging this pull request may close these issues.

2 participants