【问题标题】:Change/update a variable in Handlebars JS from the parent context inside a loop从循环内的父上下文更改/更新 Handlebars JS 中的变量
【发布时间】:2018-01-29 15:47:08
【问题描述】:

我已经看到了很多关于如何访问循环内属于父上下文的变量的示例。但是,我不仅需要访问变量,还需要更改/更新它。

正如您在下面看到的,我有一个设置变量的自定义助手,但是当我尝试在循环内更改该变量时,它不起作用。有没有办法让它工作?

请看看这个jsFiddle。

模板

{{setVarWithName "test" "hello"}}
{{#each questions}}
    <h3>{{title}}</h3>
    <p>before update: {{../test}}</p>
    {{setVarWithName "test" "goodbye"}}
    <p>after update: {{../test}}</p>
    <hr />
{{/each}}

Handlebars init with helper

var source = $("#template").html(); 
var template = Handlebars.compile(source); 

var data = {
  "questions": [
     {"title": "Question 1"},
     {"title": "Question 2"}
   ]
}; 

Handlebars.registerHelper('setVarWithName', function (name, value) {
    this[name] = value;
    return '';
});

$('body').append(template(data));

【问题讨论】:

    标签: javascript jquery html handlebars.js handlebarshelper


    【解决方案1】:

    答案,就像在 JavaScript 中经常出现的一样,是作用域。基本上,当在{{#each}} 循环内使用时,助手setVarWithName 内部的this 不会指向data 变量,但它确实指向question[@index]。你需要做什么:

    var source = $("#template").html(); 
    var template = Handlebars.compile(source); 
    
    var data = {
      "questions": [
         {"title": "Question 1"},
         {"title": "Question 2"}
       ]
    }; 
    
    Handlebars.registerHelper('setVarWithName', function (name, value) {
        data[name] = value; // changed from this to data
        return '';
    });
    
    $('body').append(template(data));
    

    查看我的工作fiddle。为了便于阅读,我添加了 {{s}} 助手以将渲染的 this 打印到模板中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2021-06-29
      • 1970-01-01
      • 2020-10-23
      • 1970-01-01
      相关资源
      最近更新 更多