Handlebars模板未填充上下文

Handlebars template not filling in context

本文关键字:填充 上下文 Handlebars      更新时间:2023-10-28

我正在构建一个Flask应用程序,并有一些客户端HTML呈现,我想使用Handlebars模板来完成。

我有以下非常基本的车把模板:

<script id="source-template" type="text/x-handlebars-template">
    <div class="source-data">
        <span>{{last4}}</span>
        <span>Exp : {{exp_month}} / {{exp_year}}</span>
    </div>
</script>

我使用它如下(与车把教程中完全一样):

var source = $('#source-template').html();
var template = Handlebars.compile(source);
var context ={
    last4:'1234',
    exp_month:'12',
    exp_year:'2020'
};  
var html = template(context);
console.log(html);

然而,它似乎并没有将上下文中的数据插入到模板中。控制台输出为:

<div class="source-data">
    <span></span>
    <span>Exp : / </span>
</div>

我是不是遗漏了什么?我不确定可能出了什么问题,因为我基本上复制了车把的例子。

由于我使用的是Flask,所以我在一个由Jinja呈现的html文件中编写了脚本。

因为没有名为last4exp_monthor exp_year的变量传递到Flask的render_template()函数中,所以它将它们替换为零,从而使车把模板没有变量。

解决方案是在脚本中使用{% raw %},这样Jinja就不会将这些解释为变量:

<script id="source-template" type="text/x-handlebars-template">
    {% raw %}
    <div class="source-data">
        <span>{{last4}}</span>
        <span>Exp : {{exp_month}} / {{exp_year}}</span>
    </div>
    {% endraw %}
</script>