JsRender - nested #index

https://github.com/BorisMoore/jsrender/issues/96#issuecomment-4654107

by johnpapa

HTML

<script src="http://borismoore.github.com/jsrender/jsrender.js"></script>
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div id="target"></div>

<script id="myTmpl" type="text/x-jsrender">
<table class="table table-bordered table-condensed table-striped">
    <thead class="label">
        <tr>
            <td>#</td><td>Location</td><td>Name</td><td>Phone</td>
        </tr>
    </thead>
    <tbody>
        {{for locations}}
        {{for people ~firstLevelIndex=#index+1 ~location=#data.name}}
        {{for phones ~secondLevelIndex=#index+1 ~person=#data.name}}
        <tr>
            <td>
                {{:~firstLevelIndex}}.{{:~secondLevelIndex}}.{{:#index+1}}
            </td>
            <td>{{:~location}}</td>
            <td>{{:~person}}</td>
            <td>{{:number}}</td>
        </tr>
        {{/for}}
        {{/for}}
        {{/for}}
    </tbody>
</table>
<ul>
    {{for locations}}
    <li>{{:#index+1}}) {{:name}}
        <ul>
            {{for people ~firstLevelIndex=#index+1}}
            <li>{{:~firstLevelIndex}}.{{:#index+1}}) {{:name}}
                <ul>
                    {{for phones ~secondLevelIndex=#index+1}}
                    <li>
                        {{:~firstLevelIndex}}.{{:~secondLevelIndex}}.{{:#index+1}}) {{:number}} 
                        {{if type==="cell"}} is a cell phone ( inside an 'if', #index = {{:#index}} ){{/if}} 
                        ( outside the if, #index = {{:#index}} )
                    </li>
                    {{/for}}
                </ul>
            </li>
            {{/for}}
        </ul>
    </li>
    {{/for}}
</ul>
</script>

JavaScript

var
data = {
    locations: [
        {
        name: 'Florida',
        people: [
            {
            name: "John",
            phones: [{
                type: "work",
                number: "111-456-7890"},
            {
                type: "home",
                number: "222-456-7890"}]},
        {
            name: "Colleen",
            phones: [{
                type: "cell",
                number: "444-456-7890"},
            {
                type: "home",
                number: "555-456-7890"}]}
        ]},
    {
        name: 'New York',
        people: [
            {
            name: "Landon",
            phones: [{
                type: "cell",
                number: "777-456-7890"},
            {
                type: "home",
                number: "888-456-7890"}]}]}

    ]
};

$('#target').html($('#myTmpl').render(data));