简体   繁体   中英

Unable to get the HTML result by executing a Handlebars template with a context

I have the following code in my javascript:

    var context = {
        "title": section_title
    };

    var section_template = $("section-template").html(),
        template = Handlebars.compile(section_template);

    alert("yeah!");
    alert(context.title);
    var final_section_content = template(context);

    alert("WHat?");

The alerts() are there purely for debugging purposes.

section_template is correctly populated with the template that I prepared

template has a function as its value so I assume the compilation went well too.

The "yeah!" and the title of the context are displayed correctly. However, something seems to be going wrong in the template(context); execution. The "What?" alert is never raised, and thus the HTML content is never set (later in the program). Later in the program, I use the final_section_content as the value for the jQuery before() function. But the "What?" itself is not being executed. Any idea why?

Template Code:

<script id="section-template" type="text/x-handlebars-template">
    <div class="row-fluid">
        <div class="span8 offset1">
            {{! This will contain the section requirements}}
            <div class="section-title">
                <span class="add-on">
                    <i class="icon-plus-sign"></i>
                </span>

                <h2>
                    {{title}}
                </h2>
                <i class="icon-list" data-placement="bottom" data-title="Create sub-section"></i>
                <i class="icon-pencil" data-placement="bottom" data-title="Edit section title"></i>
                <i class="icon-trash" data-placement="bottom" data-title="Delete section"></i>
                <div class="subsection">
                    {{! Dummy container for subsection}}
                </div>
            </div>
        </div>
        <div class="span2 offset1">
            {{! This will contain the total score for the section}}
        </div>
    </div>
</script>

Make sure that the element containing the template code is loaded prior to querying it's contents using $('#section-template').html() . See Why is browser returning error "TypeError: this._input is null" in Firefox (and similar in Chrome) when using handlebars.js? for more details.

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