I have a webservice that returns an item, which could be one of several types. I want to .template it using jquery, and depending on what type of object it is, use the appropriate template.
I am wondering what the best way is of storing the various templates. I figured putting them into one file called ItemTemplates.js or whatever would be fine, and each one would have a name such as Cat_Template Dog_Template and I could use a switch{} to load the cor开发者_StackOverflowrect one based on the type of object returns.
Can jquery templates be stored in a js file? Is there another good way of doing this? I'm using asp.net so perhaps a solution lies there?
The excellent jQote (overview, latest version) is a flexible templating library for jQuery. From the docs:
<script type="text/html" id="template">
<![CDATA[
<p class="greetings">
Hello <%= this.name %>, how are you doing?
May I offer you
<% this.is_starving() ? %>
some tasty peasant?
<% : %>
a refreshing Singha?
<% ; %>
</p>
]]>
</script>
You can store as many/few of these script blocks as you like in a single file, I generally lump them into the main .js
with the rest of my code. As they are standard HTML script tags they can also go into your main page, or be loaded in via AJAX and written to the document.
I have built a lightweight template manager that loads templates via Ajax, which allows you to separate the templates into more manageable modules. It also performs simple, in-memory caching to prevent unnecessary HTTP requests. (I have used jQuery.ajax here for brevity)
var TEMPLATES = {};
var Template = {
load: function(url, fn) {
if(!TEMPLATES.hasOwnProperty(url)) {
$.ajax({
url: url,
success: function(data) {
TEMPLATES[url] = data;
fn(data);
}
});
} else {
fn(TEMPLATES[url]);
}
},
render: function(tmpl, context) {
// Apply context to template string here
// using library such as underscore.js or mustache.js
}
};
You would then use this code as follows, handling the template data via callback:
Template.load('/path/to/template/file', function(tmpl) {
var output = Template.render(tmpl, { 'myVar': 'some value' });
});
If you are referring to storing something like this in a javascript file:
<script id="myTemplate" type="text/x-jquery-tmpl">
<li>
<a href="${Url}" target="_blank">${Text}</a>
</li>
</script>
It's just not possible like that because that's HTML and .js files aren't parsed for HTML. The only alternative that I can think of is to generate such HTML dynamically from a .js file during $(document).ready() using something like
document.write('<script id="myTemplate" type="text/x-jquery-tmpl">template HTML</script>');
or
$('<script id="myTemplate" type="text/x-jquery-tmpl"></script>')
.html('template HTML')
.appendTo('body');
Haven't tested this before, so I don't know if it'll work.
精彩评论