开发者

Storing jquery/js templates in a separate files

开发者 https://www.devze.com 2023-04-02 17:34 出处:网络
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).

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

精彩评论

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