2

I am trying to learn mustache / icanhaz in conjunction with jquery and javascript, and I've got a mustache template to which I'm passing various data. One of the pieces of data is a list of choices, but that list can vary in length (say, one to three choices). How do I pass that varying data to mustache?

This is my code:

Javascript:

for (childIndex in scenes[sceneID].children) {
    childSceneID = scenes[sceneID].children[childIndex];
    childScene = scenes[childSceneID];
    childLink = childScene.name;
}

decision = ich.decision(decisionData);
$('#page_container').append(decision);

Template:

<script id="decision" type="text/html">
        <div id="page">
            <h1>{{ tTitle }}</h1>
            <ul id="options">
                <li>{{tDecision}}</li>
            </ul>
            {{#tBacklink}}<a id="back" data-sceneid="{{tBacklink}}">Back</a>{{/tBacklink}}
        </div>
    </script>

So somehow I have to pass all the childLinks in the decision object to mustache to be parsed in a loop to output the list of <li> elements.

Anybody know how to do this?

1 Answer 1

5

Model your data in an object first of all,

var scene = {
  tTitle: '',
  tDecision: '',
  tBacklink: ''
};

Then place each of these objects in an array on each iteration of your loop

var scenes = [];

for () {
  scenes.push(scene);
}

Then call Mustache to render the template with the scenes array, the template has been modified like this

<script id="decision" type="text/html">
  <div id="page">
    {{#scenes}}
      <h1>{{ tTitle }}</h1>
      <ul id="options">
        <li>{{tDecision}}</li>
      </ul>
      {{#tBacklink}}<a id="back" data-sceneid="{{tBacklink}}">Back</a>{{/tBacklink}}
    {{/scenes}}
  </div>
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

Well, the only thing is - it's not all of the data that needs to be looped through, it's only tDecision that would have multiple values. I think I am going to delete this question - I started a new one here that might be clearer and more to the point: stackoverflow.com/questions/7071193/…
Basically, I have something that is working, only it is not spitting out a separate li for each tDecision, it just generates a comma delimited list
If you post some code I can take a look. Surely you can figure out where to go from here based on my answer? To debug, log the array before templating and log the html afterwards.
Yes - I think I can figure it out. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.