javascript - 如何缓存 mustache 模板?

标签 javascript templates caching external mustache

我想缓存 mustache 模板。

我知道我可以直接包含 mustache 模板,就像这样:

<script id="mustache-template" type="text/html">
<h1>{{title}}</h1>
</script>

然后用 javascript 调用它们,像这样:

var html, template, data;
data = {  
    title : "Some title"
}; 
template = document.getElementById('mustache-template').innerHTML;
html = Mustache.to_html(template, data);

这不会缓存模板。我唯一能弄清楚的方法是使用链接标签,但是如何在没有 ajax 请求的情况下通过 javascript 调用模板内容?

这行不通(当然)...

HTML

<link type="text/html" href="/mustache/template.tpl" id="mustache-template" />

Javascript

document.getElementById('mustache-template').innerHTML;

最佳答案

这个问题很有意思!几个月前,当我开始在 Rails 项目中使用 mustache 进行“巨大的”前端模板时,我遇到了同样的问题。

我最终得到了以下解决方案......


Mustache 模板位于公共(public)文件夹中:

/public/templates/_template_name.tpl

每当我需要一个模板时,我都会使用这个助手 getTemplate 来做一些事情(有一些 mootools,但也有评论):

// namespace.templatesCache is an object ( {} ) defined inside the main app js file

var 
    needXHR = false, // for callback function
    templateHTML = ""; //template html

if(!(templateHTML = namespace.templatesCache[template_name])){ //if template is not cached

    templateHTML = (this.helpers.supportLocalStorage) ? localStorage.getItem(template_name) : ""; //if browser supports local storage, check if I can retrieve it

    if(templateHTML === "" || templateHTML === null){ // if I don't have a template (usually, first time), retrieve it by ajax

      needXHR = true;  

      new Request.HTML({ //or jQuery's $.get( url /*, etc */ ) 

          url: namespace.URLS.BASE+"templates/_"+template_name+".tpl", // url of the template file

          onSuccess : function(t, e, html, js){

                namespace.templatesCache[template_name] = html; //cache it

                if(_this.helpers.supportLocalStorage){ //and store it inside local storage, if available
                  localStorage.setItem(template_name,html); 
                }

                //call callback      
          }
      }).get();

    }else{ //retrieved by localStorage, let's cache it

        namespace.templatesCache[template_name] = templateHTML;

    }

}

if(!needXHR){ // I retrieved template by cache/localstorage, not by Ajax

    //call callback    

}

我这样称呼这个助手:

namespace.helpers.getTemplate('template_name', function( templateHTML ){
    // the callback function
});

你可以注意到第一次用户需要模板时,有一个异步请求(如果你不想在回调中包装一些其他代码,你可以发出一个同步请求)

我希望它能有所帮助,我很乐意收到有关这些东西的反馈/建议 :)

关于javascript - 如何缓存 mustache 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6292584/

相关文章:

javascript - Three.js 3D立方体在重新初始化时旋转越来越快

c++ - 捕获具有特定模板参数的类

c++ - friend &&模板

c++ - 模板函数重载 : enable_if for CRTP, 编译器坚持选择泛型函数

android - 播放流时如何避免 Android Media Player 中的 15 秒延迟/缓存

c# - CacheItemUpdateCallback 中的 HttpContext.Current Null

javascript - 了解递归函数在 javascript 中的工作原理

php - 两个域,一个站点,一个 SSL 结帐。如何获得 cookies ?

java - 如何使 Ehcache 永远不会从磁盘存储中逐出?

Javascript 未正确填充输入值