search

Home  >  Q&A  >  body text

node.js - Express模板引擎handlebars里面{{#each XXX}}中使用locals.xx 不起作用的

就是设置了

res.locals.username = xxx

然后页面里面想要在{{#each}}里使用username

{{#each 不管是什么}}
   <p>{{username}}</p>
{{/each}}

username是没有值的

要怎么样才能在{{#eac}}里使用locals.xx呢



伊谢尔伦伊谢尔伦2786 days ago393

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-04-17 15:31:37

    This is the right usage.

    1. First ensure that username has a value.

    2. cannot appear in a recursive partial.

    If it is not recursive partial and there is still no output value, then it must be that username has no value, not handlebars.

    Furthermore, you didn’t say which handlebars implementation you used? Is it Express integrated hbs or handlebars? If it's the latter, some integration work still needs to be done.

    -------------------------UPDATE--------------------- -------

    I just experimented and found that locals variables cannot be used in {{#each}}.
    I raised an issue in the hbs official repository before, thinking that locals cannot be used only in recursive partials. In fact, {{#each}} is also used in the partial I tested, and it has nothing to do with whether it is recursive or not. This should be a bug in hbs. I will update that issue to explain this problem.

    issue: https://github.com/pillarjs/h...

    ------------------------UPDATE---------------------- ----------

    Let me provide you with a temporary solution first:

    Add loginUserPhoto to the render context, and then use {{@root.loginUserPhoto}} in {{#each}} to access it.

    reply
    0
  • Cancelreply