iLemming
iLemming

Reputation: 36166

Complex jQuery templates

Using jQuery templates is easy for some simple data structures.

<script type="jquery/x-jquery-tmpl" id="myTemplate">
  <li> ${Element} </li>
</script>

var elements = [
   { Element: "Hydrogen" },
   { Element: "Oxygen"   },
   { Element: "Nitrogen" }
];

$("#elementsPlaceholder").replaceWith($("#myTemplate").tmpl(elements));

But if I need a template for more complex data? Something like:

<script type="jquery/x-jquery-tmpl" id="myTemplate">
  <div> ${Molecule} </div>
  consists of:
  <ul>
      <li> ${Element} </li>
  </ul>
</script>

How can apply data to that? Is it possible? Could you show me an example?

Upvotes: 0

Views: 314

Answers (1)

Mike Samuel
Mike Samuel

Reputation: 120496

<ul>
    <li> ${Element} </li>
</ul>

should use {{each}}

<ul>
  {{each Elements}}<li>${$value.Element}</li>
</ul>

and then you pass in both the molecule and the elements

$("#elementsPlaceholder").replaceWith($("#myTemplate").tmpl({
  Molecule: ...
  Elements: [{ Element: "Hydrogen" }, ...]
}))

Upvotes: 2

Related Questions