I have a piece of template HTML that is returned from a Javascript function:
function getTemplate() {
return '<li id="element_idx_" class="elementChoice">' +
' <a href="#" onclick="_clickScript_" tabindex="27" title="_toolTip_">' +
' <span id="element_idx_title">_elementDisplayText_</span>' +
' <div class="elementIcon" id="element_idx_image"></div>' +
' <div class="actionIcon" id="element_idx_Icon"></div>' +
' </a>' +
'</li>';
}
The substrings _idx_
, _clickScript_
, etc., are substituted using data retrieved from an AJAX call, using a function whose definition is similar to:
function interpolate(template, replacements) {
// * template is the HTML listed above
// * replacements is a JavaScript object, where the property names map to
// the substitution strings in the HTML template.
//
// E.g., { idx: 4, clickScript: function() { // click }, displayName: foo }
}
As you can see, some items are replaced multiple times within the template (i.e., _idx_
).
开发者_JAVA技巧The webapp already uses jQuery extensively throughout, so I'm wondering if there's a more jQuery-esque way of achieving this, perhaps using the DOM, rather than relying on string manipulation.
Any thoughts?
Well John Resig has blogged about putting templates like that into script blocks:
<script id='template1' type='text/html'>
<li id='element_idx' ...
...
</li>
</script>
The browsers won't try to interpret those, but you can get the text:
var template = $('#template1').text();
It's a little cleaner than putting your template in the Javascript like that, but it's not without its problems. Separating the template from the code might be a little painful or awkward, depending on your setup.
There isn't since you replace those strings in places that are hard to reach with DOM operations (like element_idx_Icon
).
精彩评论