【问题标题】:Populate external .html file with moustache?用小胡子填充外部 .html 文件?
【发布时间】:2015-04-15 15:10:00
【问题描述】:

假设我有 jQuery 代码将外部 html 文件加载到模板中。

$('#myButton').click(function(){
  $('#content').load('file.html');
});

现在,我想填充file.html 文件中的一些字段。这可能吗?

【问题讨论】:

  • 考虑在此处包含file.html 的内容(或者至少是它可能包含的一个很好的代表性示例)。

标签: javascript hogan.js


【解决方案1】:

这是一个(未经测试的)示例,说明您可以如何做到这一点。

$('#myButton').click(function() {

  // load text into a hidden div.
  $('#hiddenContent').load('file.html', function() {

    // grab template from hidden div
    var templateString = $('#hiddenContent').html();

    // compile the template string into a template object
    var compiledTemplate = hogan.compile(templateString);

    // apply some data to the template
    var parsedTemplate = compiledTemplate.render({...some data});

    // finally, show the parsed template
    $('#content').html(parsedTemplate);
  }
});

编辑:附加说明

理想情况下,您不会将 file.html 加载到 dom 元素中,因为它不需要显示。只需加载文本。

此外,编译模板的计算成本很高。在生产环境中,这些模板应该是预编译的。 Hogan 有一个名为 Hulk 的命令行工具来执行此操作。

【讨论】:

    【解决方案2】:

    大概是这样的吧?

    $('#myButton').click(function() {
      $('#content').load('file.html', function() {
        // do something to populate fields created by the loading of file.html
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多