FladeX
FladeX

Reputation: 133

Data template at backbone.js

Tell me, please, how to create templates in Backbone.js, if there is a nested data.

Data example:

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?',
        },
    ]
}
];

And the html-code for output:

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

I understand that I should get something like this:

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

But I don't know how to display a nested array of questions in the template. Help me, please.

Upvotes: 0

Views: 259

Answers (1)

T Nguyen
T Nguyen

Reputation: 3415

You can loop through an array like this:

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

Upvotes: 1

Related Questions