Question

I have an object that looks something like the code below: I don't know the names of the inner objects they could vary, how can I create a template that doesn't care about the names but loops through nested array of cards?

Cards: {
DynamicName2: [..]
DynamicName3: [..]
DynamicName4: [..]
DynamicName5: [..]
DynamicName6: [..]

}

the template

<script type="mustache/x-tmpl" id="pack_tmpl">
{{#Cards}}
 {{.}}
//foreach inner object do this:
<ul>
</ul>

{{/Cards}}
</script> 
Était-ce utile?

La solution

You will have to massage your model first in Javascript. Simply convert each named property of "Cards" into an array entry. Then pass the new model to the template when you render it:

function extractDynamicCards(model) {
  var cardModel = [];
  for (var dn in model.Cards) {
    cardModel.push(model.Cards[dn]);
  }
  return {Cards: cardModel};
}

EDIT Here are before and after example scripts

<script type="mustache/x-tmpl" id="pack_tmpl1">
<ul>
    <li>{{Cards.DynamicName2.d}}</li>
    <li>{{Cards.DynamicName3.d}}</li>
</ul>
</script>

<script type="mustache/x-tmpl" id="pack_tmpl2">
<ul>
    {{#Cards}}
      <li>{{d}}</li>
    {{/Cards}}
</ul>
</script>

<h2>Result 1</h2>
<div id="result1"></div>

<h2>Result 2</h2>
<div id="result2"></div>

for the following data:

<script type="text/javascript">
var model = {
  Cards: {
    DynamicName2: { d: "data-2" },
    DynamicName3: { d: "data-3" },
    DynamicName4: { d: "data-4" },
    DynamicName5: { d: "data-5" },
    DynamicName6: { d: "data-6" },
  }
}

function extractDynamicCards(model) {
  var cardModel = [];
  for (var dn in model.Cards) {
    cardModel.push(model.Cards[dn]);
  }
  return {Cards: cardModel};
}

var source1   = $("#pack_tmpl1").html();
var template1 = Hogan.compile(source1);
$('#result1').html(template1.render(model));

var source2   = $("#pack_tmpl2").html();
var template2 = Hogan.compile(source2);
$('#result2').html(template2.render(extractDynamicCards(model)));
</script>

You can see it all working with this JSFiddle

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top