简体   繁体   中英

How to access data inside if statement in Handlebars templates

To the handlebars (version 1.0.0-rc.3) template I am passing two variables , one is the json and the other one is the string containing the current language on site.

self.template = template({ data: self.model, lang:self.lang });

Then inside the template file I have the following structure:

    {{#each data}} 
    //this is working
    {{../lang}}   
       {{#if this.title}}   
         {{this.desc}}
         //i've tried this
         {{../lang}}
         //and this
         {{lang}}
       {{/if}}  
    {{/each}}   

...but I couldn't access the lang value inside the if statement. What am I doing wrong?

I know you already solved your issue with a workaround but registering a Helper for doing a native way is cumbersome.

The thing is that every Handlebars helper overwrites the context and nest the new one inside the parent one, so you have to go up uone step further, like a UNIX like directory.

So, to access lang inside an each->if you have to use:

{{ ../../lang }}

I've find a solution by creating a handlebars helper function:

Handlebars.registerHelper('language', function() { return self.lang; });

Then in the template i could use {{language}} where ever I want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM