【问题标题】:How to access Mustache HTML template from external <script />如何从外部 <script /> 访问 Mustache HTML 模板
【发布时间】:2013-08-08 11:38:46
【问题描述】:

我正在使用Mustache.js 来呈现 HTML 网站的不同重复部分。到目前为止,我将每个模板都放在 &lt;script /&gt; 中,并通过 jQuerys html() 方法访问其内容:

<script type="text/html" id="html-script">
    <!-- ... -->
</script>

<script type="text/javascript">
$('script[type="text/html"]').each(function() {
    var $this = $(this);
    templates[$this.attr('title')] = $this.html();
});
</script>

现在我想将每个模板放在自己的文件中,并像这样包含它们:

<script type="text/html" id="html-script" src="template.html"></script>

这不起作用所以我的问题是

  1. 为什么不呢?
  2. 如何让它工作?

我阅读了一篇关于 How to Load Mustache.js Templates From an External File with jQuery 的文章,我可以将其用作备用解决方案,但如果我不必自己 $.get() 模板,我将不胜感激。

【问题讨论】:

    标签: jquery mustache


    【解决方案1】:

    虽然w3c spec&lt;script&gt; 元素的src 的含义模糊不清,但它确实表示“如果该类型标识一种脚本语言并且资源符合该语言规范的要求。”实际上,这意味着浏览器只会加载 javascript,而您无法与以这种方式加载的 HTML 文档进行交互。

    我会重新考虑您尝试解决问题的方式。这是一个异步加载模板文件的解决方案,从有用的Christophe Conraets 窃取:

    // Asynchronously load templates located in separate .html files
    function loadTemplate (views, callback) {
        var deferreds = [];
    
        $.each(views, function(index, view) {
            if (window[view]) {
                deferreds.push($.get('tpl/' + view + '.html', function(data) {
                    window[view].prototype.template = _.template(data);
                }));
            } else {
                alert(view + " not found");
            }
        });
    
        $.when.apply(null, deferreds).done(callback);
    }
    
    loadTemplate(['view', 'view2','view3'], function() {
        // do amazing things...
    });
    

    [source] (显然,修改tpl 目录以满足您的需要)

    您也可以使用 require.js(我的首选方法)之类的方法来执行此操作。

    【讨论】:

    • 您能解释一下deferreds.push()// do amazing things 之间的魔法是如何发生的吗? :) 。 . .我的意思是,视图对象在哪里?
    【解决方案2】:

    此解决方案使用 jQuery holdReady 方法为 onReady 事件添加延迟。请注意,jquery-script 必须包含在资源加载脚本之前。

    <script src="jquery.min.js"></script>
    <script src="mustache.min.js"></script>
    
    <script id="template1" type="x-tmpl-mustache" src="template1.html"></script>
    <script id="template2" type="x-tmpl-mustache" src="template2.html"></script>
    
    <script type="text/javascript">
    $('script[type="x-tmpl-mustache"]').each(function(idx, templateSource) {
        $.holdReady(true);
        $.get(templateSource.src, function(template) {
            templateSource.text = template;
            $.holdReady(false);
        });
    });
    $(document).ready(function() {
        Console.log("All templates loaded.");
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2019-11-11
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多