understanding Jquery template
Asked Answered
A

1

7

I am reading and trying to understand a Jquery template example.

<script id="movieTemplate" type="text/x-jquery-tmpl"> 
  {{tmpl "titleTemplate"}}
  <tr class="detail"><td>Director: ${Director}</td></tr>

</script>

<table><tbody id="movieList"></tbody></table>

<script>
var movies = [
  { Name: "The Red Violin", Director: "François Girard" ,Producer : "ssss" },
  { Name: "Eyes Wide Shut", Director: "Stanley Kubrick" },
  { Name: "The Inheritance", Director: "Mauro Bolognini" }
];

/* Convert the markup string into a named template,
   referenced by the {{tmpl}} tag */
$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );

/* Render the movies data, using the named template as a nested template */
$( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );
</script>

In this example program I am not able to understand about the:

/* Convert the markup string into a named template, referenced by the {{tmpl}} tag */

when we call: $( "#movieTemplate" ).tmpl( movies ) it is calling the template on that we are calling the template function with input movies and appending that to movieslistid

if I remove the code

$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );

it does not work. Can you please explain why we need this and what is it doing here like what does: /* Convert the markup string into a named template, mean and all..

I tried to readonline and found that I am not getting this clarified

Alectryomancy answered 21/11, 2012 at 6:34 Comment(0)
O
10

This contains a reference to a template named "titleTemplate", a template which has not yet been defined:

<script id="movieTemplate" type="text/x-jquery-tmpl"> 
  {{tmpl "titleTemplate"}}
  <tr class="detail"><td>Director: ${Director}</td></tr>
</script>

This line defines that missing template:

$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );

It is another way of saying

<script id="titleTemplate" type="text/x-jquery-tmpl"> 
  <tr class='title'><td>${Name}</td></tr>
</script>

In essence the example shows that you can define templates in two ways

  • declaratively in the HTML source code, as <script type="text/x-jquery-tmpl"> elements
  • programmatically from strings through $.template()
Oldham answered 21/11, 2012 at 6:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.