This is a simple example based on the code in the jquery-tmpl API docs. I'd like to use a nested {{tmpl}} tag--here the "titleTemplate". I'd like to use various helper functions in both the outer template and the nested template. This example has one trivial helper function called "embolden" that's passed to the initial tmpl() call.
The following works. I'm able to embolden the Name data inside the titleTemplate. But it seems messy. Is there a cleaner way to do this? Since formatHelpers is passed into the original tmpl() call, is it really necessary to pass it into the {{tmpl}} tag as well?
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl($item.data, formatHelpers) "#titleTemplate"}}
<tr class="detail"><td>Director: ${$item.embolden(Director)}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${$item.embolden($item.data.Name)}</td></tr>
</script>
<table><tbody id="movieList"></tbody></table>
<script>
var formatHelpers = {
embolden: function(i) {
return "*" + i + "*";
}
};
var movies = [
{ Name: "The Red Violin", Director: "François Girard" },
{ Name: "Eyes Wide Shut", Director: "Stanley Kubrick" },
{ Name: "The Inheritance", Director: "Mauro Bolognini" }
];
/* Render the template with the movies data */
$( "#movieTemplate").tmpl(movies, formatHelpers).appendTo("#movieList");
</script>
With your example, all you need to do is
{{tmpl($item.data, $item) "#titleTemplate"}}
Code example on jsfiddle.
Another way you can do this is to define your formatHelpers in global scope you should be able to call them directly in your template.
var formatHelpers = {
embolden: function(i) {
return "*" + i + "*";
}
};
$(function() {
var movies = [
{
Name: "The Red Violin",
Director: "François Girard"},
{
Name: "Eyes Wide Shut",
Director: "Stanley Kubrick"},
{
Name: "The Inheritance",
Director: "Mauro Bolognini"}
];
$("#movieTemplate").tmpl(movies).appendTo("#movieList");
});
And inside of your template you can do the following:
<script id="movieTemplate" type="text/x-jquery-tmpl">
{{tmpl($item.data) "#titleTemplate"}}
<tr class="detail"><td>Director: ${formatHelpers.embolden(Director)}</td></tr>
</script>
<script id="titleTemplate" type="text/x-jquery-tmpl">
<tr class="title"><td>${formatHelpers.embolden(Name)}</td></tr>
</script>
Code example on jsfiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With