将 jquery/js 模板存储在单独的文件中
我试图弄清楚如何将 jQuery 模板存储在与基本 html 不同的文件中(不使用字符串或 ajax 请求)。
例如,在我的 html 页面上,我想这样做:
<script type ="text/x-jquery-tmpl" id="personTmpl" src="js/personApp.tmpl.html"></script>
<div id="container"></div>
<script type="text/javascript">
var p = { name: 'joe' };
$( "#personTmpl" ).tmpl( p ).appendTo( "#container" );
</script>
#personTmpl 将在 personApp.tmpl.html 文件(或其他地方)中定义
最终目标是将我的模板与 js 代码分开(并且html)。
我不喜欢字符串方法,因为它使较长模板的编辑变得困难。而且我也不想在加载时触发 ajax 请求(注意,模板文件最终将被聚合以用于生产)。
想法?
I am trying to figure out how to store jQuery templates in different files from the base html (without using a string or ajax request).
For instance, on my html page, I would like to do this:
<script type ="text/x-jquery-tmpl" id="personTmpl" src="js/personApp.tmpl.html"></script>
<div id="container"></div>
<script type="text/javascript">
var p = { name: 'joe' };
$( "#personTmpl" ).tmpl( p ).appendTo( "#container" );
</script>
Where the #personTmpl would be defined in the personApp.tmpl.html file (or someplace else)
The end goal is just keeping my template separate from the js code (and html).
I don't like the string method, because it makes editing hard for longer templates. And I don't want to fire an ajax request off on load either (note, the template file would eventually be aggregated for production).
Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用 requirejs 及其文本插件解决了这个问题。在开发过程中,使用 XHR 请求加载模板。部署时,我使用 requirejs r.js 文件进行优化,然后将模板包含在主 js 文件中,从而节省了许多要加载的文件。
I solved this problem using requirejs together with their text plugin. During development, the templates are loaded using an XHR request. When deployed, I optimized using the requirejs r.js file, and the templates are then included in the main js file, saving a number of files to be loaded.
我也遇到过类似的情况,我的解决方案是编写一个模板缓存对象,负责在第一次请求时通过ajax加载模板,并从那时起将其存储在内存中。它对我的项目效果相当好。如果您有兴趣,我可以发布我使用的代码。
I had a similar situation, and my solution was to write a template caching object that was responsible for loading a template via ajax the first time it was requested and storing in memory from then on. It worked rather well for my project. I can post the code i used if you are interested.