【问题标题】:Handlebars Template Not Rendering - Can See HTML In Firefox InspectorHandlebars 模板未呈现 - 可以在 Firefox Inspector 中看到 HTML
【发布时间】:2018-09-20 00:50:34
【问题描述】:

我在外部文件 (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 Inspector Output

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

Firefox Console Output

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

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

【问题讨论】:

    标签: javascript jquery html handlebars.js


    【解决方案1】:

    当您检索您的模板文件时,您会将其封装在&lt;script&gt; 标记中。 Handlebars 只需要内容。因此(正如您在 Firefox 检查器中看到的那样)编译后的输出不是可显示的 HTML,因为它仍在原始的 script 标记内。

    当您将数据分配给source 变量时,您需要从数据中提取 HTML。

    success: function( data ) {
        source = $( data ).html();
        ...
    

    【讨论】:

      【解决方案2】:

      据官方网站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
      

      【讨论】:

        猜你喜欢
        • 2017-08-02
        • 2020-07-13
        • 1970-01-01
        • 1970-01-01
        • 2011-09-01
        • 1970-01-01
        • 2021-05-26
        • 1970-01-01
        • 2015-10-27
        相关资源
        最近更新 更多