handlebars.js - Does {{#if}} affect the context? -


i have helper function error checking when getting property object (converted sample on stackoverflow):

module.exports.register = function (handlebars, options) {    handlebars.registerhelper('get', function (obj, prop, context) {     if (typeof obj !== 'object') {       throw new error('get: cannot ' + typeof obj);     }      if (typeof prop !== 'string') {       throw new error('get: property must string. type ' + typeof prop + ' not supported');     }      if (!obj.hasownproperty(prop)) {       throw new error('get: object not contain property "' + prop + '"');     }      return obj[prop];   }); } 

when use works fine:

<div>   {{get ../site.sectionnames tag}} </div> 

...however, if place within {{#if true}} element, obj undefined:

<div>   {{#if true}}     {{get ../site.sectionnames tag}}   {{/if}} </div> 

i under impression {{#if}} doesn't change context. why happening?

consider following example.
..

context:

{   id: 1,   items: ['a', 'b'] } 

template 1:

{{#each items}}   <div>outer: {{../id}}</div>   {{#if ../id}}     <div>inner: {{../id}}</div>   {{/if}} {{/each}} 

output:

outer: 1   inner:   outer: 1   inner:   

template 2: - (without outer #each block)

<div>outer: {{id}}</div> {{#if id}}     <div>inner: {{id}}</div> {{/if}} 

output:

outer: 1 inner: 1  

so, think #each creates inconsistency.

../ gives context outside current block , not parent context in json. , #if block, inner , outside context may or may not same.

so, consistent , avoid confusion, should add ../ referring values inside #if block.
example,

{{#if id}}    {{../id}} {{/if}} 

Comments

Popular posts from this blog

cakephp - simple blog with croogo -

How to group boxplot outliers in gnuplot -

bash - Performing variable substitution in a string -