从外部文件加载 jQuery 模板?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4366137/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
load jQuery-Templates from external file?
提问by Nils Riedemann
I just started using jQuery's template engine. Which looks quite nice so far. Yet i wonder if it's possible to load templates from an external file somehow. Imagine having loads of templates. This would mess up the html-code and is also not cacheable and has to be downloaded on every request.
我刚开始使用 jQuery 的模板引擎。到目前为止看起来很不错。但我想知道是否有可能以某种方式从外部文件加载模板。想象一下有大量的模板。这会弄乱 html 代码,并且也不能缓存,并且必须在每次请求时下载。
I was hoping there is a way to define them all in an external file and then load them and store the compiled templates into localStorage.
我希望有一种方法可以将它们全部定义在外部文件中,然后加载它们并将编译后的模板存储到 localStorage 中。
Does anyone have an idea how to load them from an external file?
有谁知道如何从外部文件加载它们?
回答by Floyd
you can load this template with ajax.
你可以用ajax加载这个模板。
<script>
var movies = [
{ Name: "The Red Violin", ReleaseYear: "1998", Director: "Fran?ois Girard" },
{ Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];
$.get("templates/movieTemplate.html", function(data, textStatus, XMLHttpRequest){
var markup = data; //"<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"
/* Compile markup string as a named template */
$.template( "movieTemplate", markup );
/* Render the named template */
$.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
});
</script>
You can add now the localstorage logic or an array for the loaded templates if you want to load any template only once.
如果您只想加载任何模板一次,您现在可以为加载的模板添加 localstorage 逻辑或数组。
回答by moledet
I wrote litle lib as jQuery plugin for ajax rendering html on appear block with indexDB caching in browser jQuery HTML Template Loader
我写了litle lib作为jQuery插件,用于在浏览器jQuery HTML模板加载器中使用indexDB缓存出现块上的ajax渲染html
回答by Steven Hunt
I recently wrote a javascript library to assist with this:
我最近写了一个 javascript 库来帮助解决这个问题:
https://www.github.com/stevenmhunt/tmpl.loader
https://www.github.com/stevenmhunt/tmpl.loader
You can add jsRender or any other kind of template files using the <link>
tag and they automatically register.
您可以使用<link>
标签添加 jsRender 或任何其他类型的模板文件,它们会自动注册。