如何从外部<script> </script>访问Mustache HTML模板

时间:2013-08-08 11:38:47

标签: jquery mustache

我正在使用Mustache.js呈现HTML网站的不同重复部分。到目前为止,我在<script />中包含了每个模板,并通过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. 如何让这个工作?
  3. 我阅读了一篇关于How to Load Mustache.js Templates From an External File with jQuery的文章,我可以将其用作后备解决方案,但如果我自己不需要$.get()模板,我将非常感激。

2 个答案:

答案 0 :(得分:1)

虽然w3c specsrc元素的<script>的含义容易混淆,但它确实说“资源是给定类型的脚本资源,如果该类型标识脚本语言,资源符合该语言规范的要求。“实际上,这意味着浏览器只会加载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(我的优先方法)这样做。

答案 1 :(得分:0)

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

apps