用小胡子填充外部 .html 文件?

Populate external .html file with moustache?

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

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

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

也许是这样的?

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

这是一个(未经测试的)示例,说明您可以如何执行此操作。

$('#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 的命令行实用程序可以执行此操作。