It might be easiest to explain the question with an example.
I have a handlebars template defined in an HTML page:
<script id="myTemplate" type="text/html">
<h1>{{fieldname}}</h1>
</script>
I render the template with handlebars:
var source = $("#myTemplate").html();
var template = Handlebars.compile(source);
var txt = template(jsonObj);
and txt ends up containing the rendered html text. No problem.
BUT…
say I’ve retrieved an XML file via ajax, and I’d like to use jquery to reach into it to render elements.
In order to retrieve, say, the value of the “name” child element from a parent element, I might use jquery like this:
$(xml).find('name').text()
So, I thought my template might look something like this: (NOTE THIS DOES NOT WORK!)
<script id="myTemplate" type="text/html">
<h1>{{$(this).find('name').text()}}</h1>
</script>
EDIT: Obviously, this doesn’t work.
I also tried
{{this.find('name').text()}}
and even
{{.find('name').text()}}
But none of these work, and so far I’ve been unable to find any of the JS templating systems where you can do something like this. Handlebars and DUST seem the most likely to be able to do it, but I haven’t had any luck thus far.
I’ve seen some indication that I could convert the XML to JSON and just pass that as the context, and that may indeed be the only way.
Is it easier than I’m making it out to be? Impossible?
EDIT:
After more digging, it looks like there’s just not a templating solution for Javascript out there that works interchangeably with JSON or XML Dom objects for the data context. All of them appear to assume json.
Soooo… I used one of the many jquery plugins available to convert xml2json, and pass THAT object into HandleBars and everything works swimmingly.
The only trick that I ran into is if you perform a JQUERY query on the XML data to find a particular element, what you get back is an ARRAY of XML dom objects, even if there’s only 1 result.
So, I had to do something like:
var txt = template($.xml2json($(xml).find('myelementname')[0]));
And all is good.
I may open another question about whether anyone knows of a Javascript template engine that takes either json OR xml dom objects.
You cannot do that because the template parser do not know what
thisis. In the template you can only only play with the data you provide to it.However you can take a look at Underscore templates of doT js they might be helpful to you.