Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Strange context change behavior when custom helper inside #each (v4.0.5) #1135

@zordius

Description

@zordius

Please refer to this jsfiddle: http://jsfiddle.net/7ywsdydr/ .

Base on #1028 , when a block customhelper execute options.fn(this) , the context stack should not be pushed.

Here is test 1 to confirm the behavior:

Not inside #each:
 1.IF: {{#if true}}{{name}}-{{../name}}-{{../../name}}-{{../../../name}}{{/if}}
 2.MYIF: {{#myif true}}{{name}}={{../name}}={{../../name}}={{../../../name}}{{/myif}}
 3.MYWITH: {{#mywith true}}{{name}}~{{../name}}~{{../../name}}~{{../../../name}}{{/mywith}}

The input data is:

{
    "name": "John",
    "array": [1]
}

The test 1 output is:

Not inside #each:
 1.IF: John---
 2.MYIF: John===
 3.MYWITH: ~John~~

Compare output 1.IF and 2.MYIF we can know the context is not changed when inside the {{#if}} or {{#myif}} block. The {{#myif}} helper is defined as:

Handlebars.registerHelper('myif', function(conditional, options) {
    if (conditional) {
        return options.fn(this);
    } else {
        return options.inverse(this);
    }
});

Which almost same with {{#if}}. But, when this test be placed into a {{#each}} :

Inside #each:
{{#each array}}
 1.IF: {{#if true}}{{name}}-{{../name}}-{{../../name}}-{{../../../name}}{{/if}}
 2.MYIF: {{#myif true}}{{name}}={{../name}}={{../../name}}={{../../../name}}{{/myif}}
 3.MYWITH: {{#mywith true}}{{name}}~{{../name}}~{{../../name}}~{{../../../name}}{{/mywith}}
{{/each}}

Output will be:

Inside #each:
 1.IF: -John--
 2.MYIF: ==John=
 3.MYWITH: ~~John~

Note on difference between 1.IF and 2.MYIF . The issue is: when {{#if}} do not change the context, in the same time {{#myif}} changed the context. Why?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions