0

请告诉我,如果有嵌套数据,如何在 Backbone.js 中创建模板。

数据示例:

var questions = [
    {
        id: 0,
    question: [
        {
            id: 101,
            text: 'What is your name?',
        },
        {
            id: 102,
            text: 'What is your lastname?',
        },
        {
            id: 103,
            text: 'What is yout sex?',
        },
        {
            id: 104,
            text: 'How old are you?',
        },
    ]
}
];

以及用于输出的 html 代码:

<div id="qu_0" class="questions"><div>
    <p><input type="radio" rel="question" name="question_0" id="i101" value="101" /><label for="i101">What is your name?</label></p>
    <p><input type="radio" rel="question" name="question_0" id="i102" value="102" /><label for="i102">What is your firstname?</label></p>
    <p><input type="radio" rel="question" name="question_0" id="i103" value="103" /><label for="i103">What is your sex?</label></p>
    <p><input type="radio" rel="question" name="question_0" id="i104" value="104" /><label for="i104">How old are you?</label></p>
    <button type="button" name="next"><b>Answer</b></button>
</div></div>

我知道我应该得到这样的东西:

<script id="questionTemplate" type="text/template">
<div>
    <p><input type="radio" rel="question" name="question_<%= id %>" id="i<%= q.id %>" value="<%= q.id %>" /><label for="i<%= q.id %>"><%= q.text %></label></p>
    <button type="button" name="next"><b>Answer</b></button>
</div>
</script>

但我不知道如何在模板中显示嵌套的问题数组。请帮帮我。

4

1 回答 1

1

您可以像这样循环遍历数组:

<script id="questionTemplate" type="text/template">
    <% for(var question in questions) { %>
        <div id="qu_<%= question.id %>" class="questions"><div>
        <% for(var q in questions,question) { %>
            <p><input type="radio" rel="question" name="question_<%= q.id %>" id="i<%= q.id %>" value="<%= q.id %>" /><label for="i<%= q.id %>"><%= q.text %></label></p>
        <% } %>
        </div></div>
    <% } %>
    <button type="button" name="next"><b>Answer</b></button>
</script>
于 2013-09-27T19:07:18.337 回答