首页 > 解决方案 > Handlebars 模板未呈现 - 可以在 Firefox Inspector 中看到 HTML

问题描述

我在外部文件 (user-listing-template.html) 中有一个把手模板,我通过 JQuery Ajax 调用动态加载该文件以检索文件,通过 Handlebars.compile 进行编译,然后在 div 中显示。请参见下面的示例代码:

模板文件:

<script id="user-listing-template" type="text/x-handlebars-template">
  <h2 class="ui header">User Maintenance</h2>
  <hr>
  <h4 class="text-align-left">Total Users: </h4>
  <br><br>
</script>

加载模板的JS函数:

function userListroute() {
var source;
    var template;

    $.ajax({
        url: "/templates/user-listing-template.html",
        cache: true,
        success: function(data) {
            console.log('Template Data From File: ' + data);
            source = data;
            console.log('Template HTML ' + source);
            template = Handlebars.compile(source);
            console.log('Compiled Template: ' + template);

            $('#app').html(template);

        }               
    });  
}

在 index.html 中,我有一个 div,我希望在其中看到模板:

<div id="app"></div>

但是,当我运行此应用程序时,不会呈现模板。我可以在 Firefox 开发工具的 Inspector 中看到模板的 HTML 代码:

Firefox 检查器输出

所有的 console.log() 语句都显示了有效的 HTML 代码,但是它不会显示,我只看到空白页。控制台输出如下所示:

Firefox 控制台输出

我显然做错了什么,只是不确定是什么——除了渲染位之外,一切似乎都在工作。

非常感谢任何帮助。我对 Handlebars 还很陌生,我只是在尝试一个概念验证应用程序。

标签: javascriptjqueryhtmlhandlebars.js

解决方案


根据官方网站http://handlebarsjs.com/。您只需编译模板而不生成 html。

template = Handlebars.compile(source);
var html = template(yourdata);     // yourdata is the object rendered to your template
$('#app').html(html);   // can not be template variable, variable html is final html content

推荐阅读