简体   繁体   English

Handlebars.js-如何在模板中使用JS中的变量?

[英]Handlebars.js - How to use variables from JS in the template?

I am still new to Handlebars and templating in general and I am trying to assign input names based on a variable in my JS. 我对Handlebars和模板仍然不熟悉,我正在尝试根据JS中的变量分配输入名称。 For example: 例如:

HTML: HTML:

<script id="radio-template" type="x-handlebars-template">
    {{#each this}}
        <input name='{{answerSet}}' type='radio' value='{{@index}}' >{{this}}<br>
    {{/each}}
  </script>

JS: JS:

quiz(number) {
    var quizName = "quiz" + number;
    function createRadios() {
        var radioScript = $("#radio-template").html();
        var template = Handlebars.compile(radioScript);
        Handlebars.registerHelper('answerSet', function() {
            return quizName;
        });  
        $("#question").append(template(allQuestions[counter].choices));
    };
};

The result works, except radio button names are undefined. 除单选按钮名称未定义外,结果有效。 Can anyone tell me how to make the radio names equal to the quizName variable? 谁能告诉我如何使单选名称等于quizName变量? For more detail, here is the codepen: http://codepen.io/Jake_Ratliff/pen/wKoKJX?editors=101 有关更多详细信息,请参见代码笔: http ://codepen.io/Jake_Ratliff/pen/wKoKJX?editors=101

Since you've created answerSet as a helper, you'll need to call it as one in your template: 由于已将answerSet创建为帮助程序,因此需要在模板中将其作为一个进行调用:

<script id="radio-template" type="x-handlebars-template">
    {{#each this}}
        <input name='{{#answerSet}}{{/answerSet}}' type='radio' value='{{@index}}' >{{this}}<br>
    {{/each}}
  </script>

Note the # and closing answerSet above. 注意上面的#和结束answerSet

Otherwise, Handlebars assumes you're looking for a property called answerSet in the current this context; 否则,把手假设你正在寻找一个叫做物业answerSet在目前this情况下, since none exists, it returns undefined . 由于不存在,因此返回undefined

To make things a little easier, I might have your answerSet helper generate the entire input and take index and this as params. 为了使事情变得容易一些,我可能会让您的answerSet帮助程序生成整个输入并将indexthis作为参数。 That way, you're not calling a helper (with giant helper syntax) in the middle of an element. 这样,您就不会在元素中间调用辅助程序(具有巨大的辅助程序语法)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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