Monday, May 20, 2024
87
rated 0 times [  92] [ 5]  / answers: 1 / hits: 38946  / 13 Years ago, thu, february 9, 2012, 12:00:00

I would like to use handlebars.js or mustache.js to iterate over a list of families, and then iterate over that family's members. Inside of both loops, I want to display properties of both. However, once I get into the second iteration, none of the family variables are visible.



{{#each families}}
{{#each members}}
<p>{{ ( here I want a family name property ) }}</p>
<p>{{ ( here I want a member name property ) }}</p>
{{/each}}
{{/each}}


Is this possible? I'd greatly appreciate any help!


More From » handlebars.js

 Answers
18

You can nest sections easily with lists of objects. Use a data structure where families is a list that has an object members that has a list of any objects (or even more lists)like:



{
families : [
{
surname: Jones,
members: [
{given: Jim},
{given: John},
{given: Jill}
]
},
{
surname: Smith,
members: [
{given: Steve},
{given: Sally}
]
}
]
}


You would be able to populate a template like:



<ul>
{{#families}}
<li>{{surname}}
<ul>
{{#members}}
<li>{{given}}</li>
{{/members}}
</ul>
</li>
{{/families}}
</ul>


jsFiddle is currently down so here's the full working HTML with JS:



<!DOCTYPE html>
<head>

<script src=http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.3.0/mustache.min.js></script>
<script src=http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js></script>
<script>
$(function() {
var tpl = $('#fam').html(),
data = {
families : [
{
surname: Jones,
members: [
{given: Jim},
{given: John},
{given: Jill}
]
},
{
surname: Smith,
members: [
{given: Steve},
{given: Sally}
]
}
]
},
html = Mustache.to_html(tpl, data);

$(#main).append(html);

});
</script>

</head>

<div id=main></div>

<script type=template/text id=fam>
<ul>
{{#families}}
<li>{{surname}}
<ul>
{{#members}}
<li>{{given}}</li>
{{/members}}
</ul>
</li>
{{/families}}
</ul>
</script>

[#87579] Tuesday, February 7, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
louiseb

Total Points: 368
Total Questions: 107
Total Answers: 107

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;