开发者

Storing jquery/js templates in a separate files

I am trying to figure out how to store jQuery templates in different files from the base html (wi开发者_高级运维thout 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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜