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

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

本文关键字:变量 js js- Handlebars      更新时间:2023-09-26

我对Handlebars和模板还是个新手,我正在尝试根据JS中的一个变量分配输入名称。例如:

HTML:

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

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));
    };
};

结果是有效的,除了单选按钮名称未定义。有人能告诉我如何使无线电名称等于quizName变量吗?有关更多详细信息,请参阅代码笔:http://codepen.io/Jake_Ratliff/pen/wKoKJX?editors=101

由于您已经创建了answerSet作为助手,因此您需要将其称为模板中的一个:

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

注意上面的#和关闭answerSet

否则,Handlebars假设您正在当前this上下文中查找名为answerSet的属性;由于不存在,则返回undefined

为了让事情变得简单一点,我可能让您的answerSet助手生成整个输入,并将indexthis作为参数。这样,就不会在元素中间调用助手(使用巨大的助手语法)。