views:

149

answers:

2

Prototype's Template class allows you to easily substitute values into a string template. Instead of declaring the Template source-string in my code, I want to extract the source-string from the DOM.

For example, in my markup I have an element:

<div id="template1">
  <img src="#{src}" title="#{title}" />
</div>

I want to create the template with the inner contents of the div element, so I've tried something like this:

var template = new Template($('template1').innerHTML);

The issue is that Internet Explorer's representation of the innerHTML omits the quotes around the attribute value when the value has no spaces. I've also attempted to use Element#inspect, but in Internet Explorer I get back a non-recursive representation of the element / sub-tree.

Is there another way to get a Template-friendly representation of the sub-tree's contents?

+1  A: 

Looks like you can embed the template source inside a textarea tag instead of a div and retrieve it using Element#value.

Certainly makes the markup a little weird, but it still seems reasonably-friendly to designers.

Additionally, as Jason pointed out in a comment to the original question, including the img tag in the textarea prevents a spurious request for an invalid image.

Duncan Beevers
+1  A: 

Resig to the rescue:

You can also inline script:

<script type="text/html" id="user_tmpl">
  <% for ( var i = 0; i < users.length; i++ ) { %>
    <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li>
  <% } %>
</script>

Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into your page. I like to use this technique for quick-and-dirty cases where I just need a little template or two on the page and want something light and fast.

and you would use it from script like so:

var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);
Crescent Fresh