【问题标题】:Mustache, using external templates小胡子,使用外部模板
【发布时间】:2019-08-07 21:04:55
【问题描述】:

我正在阅读有关使用 Mustache.js 进行模板化的内容。我不明白的是如何放置模板。我不会将它们放在同一个文件中。

$.get('test.htm', function(templates) {
    // Fetch the <script /> block from the loaded external
    // template file which contains our greetings template.
    var template = $(templates).filter('#tpl-greeting').html();
    $('body').append(Mustache.render(template, templateData));
});


//test.htm 
<script id="tpl-greeting" type="text/html">
<dl>
    <dt>Name</dt>
    <dd>{{name}}</dd>
    <dt>Time</dt>
    <dd>{{timeNow}}</dd>
</dl>
</script>

我必须创建一个控制器来返回我的模板还是可以引用它?

【问题讨论】:

    标签: javascript jquery mustache


    【解决方案1】:

    有几种方法可以做到这一点。

    1. 如果您使用像 PHP 这样的服务器端脚本语言,只需将它们包含在 JS 中的一个单独的 .mst(扩展名实际上可以是您想要的任何内容)文件中。例如, var _templateName = &lt;?= JS::mustache('content/templateName.mst') ?&gt;;。因此,当实际渲染 JS 时,它会使用标记进行渲染,但代码仍然是可维护的。此外,通过这种方法,如果您使用的是 CDN,您的网站将受益于缓存的 JS。
    2. 另一种方法是使用任何 jQuery 的$.get$.getJSON 等方法加载外部 HTML 文件。更详细的实现是given here

    【讨论】:

    • 感谢您的回答,但我不明白。为什么不让控制器返回“填充”的 html 并执行 $("#old").replaceWith("#new");
    • @user874774 你绝对可以。但是您仍然需要构造带有新数据值的新 HTML 以在您的 replaceWith 方法中使用。模板为您完成了这项工作,加上使用模板可以实现统一和整洁。
    【解决方案2】:

    2018 年使用 fetch 代替 jQuery 的替代方案:

    fetch('template.mst')
    .then(response => response.text())
    .then(template => {
        Mustache.parse(template);
        var output = Mustache.render(template, data);
        return document.getElementById('target').innerHTML = output;
    }).catch(error => console.log('Unable to get the template: ', error.message));
    

    【讨论】:

      【解决方案3】:

      您可以将模板放在单独的文件中,就像使用 CSS 和 JS 一样。您可以使用Chevron 从文件中加载外部模板,如下所示:

      您在模板中添加指向模板文件的链接:

      <link href="path/to/template.mustache" rel="template" id="templateName"/>
      

      然后,在你的 JS 中你可以像这样渲染你的模板:

      $("#templateName").Chevron("render", {name: "Slim Shady"}, function(result){
          // do something with 'result'
          // 'result' will contain the result of rendering the template
          // (in this case 'result' will contain: My name is Slim Shady)
      });
      

      Chevron 的文档将提供更多示例

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-14
        • 2012-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多