javascript和小胡子-将数组传递给模板

javascript和小胡子-将数组传递给模板

问题描述:

我正在尝试与jquery和javascript一起学习胡须/icanhaz,并且我有一个胡须模板,可以将各种数据传递给该模板.数据之一是选项列表,但是该列表的长度可以不同(例如,一到三个选项).如何将这些变化的数据传递给胡须?

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?

这是我的代码:

JavaScript:

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);

模板:

<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>

所以我必须以某种方式将决策对象中的所有childLink传递给胡须,以便在循环中进行解析,以输出<li>元素的列表.

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.

有人知道该怎么做吗?

首先在对象中对数据建模,

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);
}

然后调用Mustache以使用scenes数组渲染模板,模板已经像这样修改

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>