简体   繁体   中英

Handlebars template not filling in context

I'm building a Flask application and have some client-side HTML rendering which I would like to do using Handlebars templates.

I have the following very basic handlebars template:

<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>

And I am using it as follows (exactly as in the handlebars tutorial):

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

However it doesn't seem to be inserting the data from my context into the template. The console output is:

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

Am I missing something here? I'm not sure what could be going wrong, as I essentially copied the handlebars example .

Since I am using Flask , I had the script written in an html file which was rendered by Jinja .

Because there were no variables named last4 , exp_month , or exp_year passed into Flask's render_template() function, it replaced them with nothing, leaving the handlebars template with no variables.

The solution for this was to use {% raw %} around the script so that Jinja wouldn't interpret these as variables:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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