Multidimensional array with jquery templates

2019-07-12 20:56发布

问题:

I have the following javascript object

var arr = [
    [
        { "id": 1, "name": "one" },
        { "id": 2, "name": "two" },
        { "id": 3, "name": "three" }
    ],
    [
        { "id": 4, "name": "four" },
        { "id": 5, "name": "five" },
        { "id": 6, "name": "six" }
    ],
]

I'm trying to use jquery templates to create the following HTML

<div class="row">
    <div class="cell">
        <span>1</span> : <span>one</span>
    </div>
    <div class="cell">
        <span>2</span> : <span>two</span>
    </div>
    <div class="cell">
        <span>3</span> : <span>three</span>
    </div>
</div>
<div class="row">
    <div class="cell">
        <span>4</span> : <span>four</span>
    </div>
    <div class="cell">
        <span>5</span> : <span>five</span>
    </div>
    <div class="cell">
        <span>6</span> : <span>six</span>
    </div>
</div>

I am using the following templates with no luck :(

<script id="rowTemplate" type="text/x-jQuery-tmpl">
    <div class="row">
        {{tmpl "#cellTemplate"}}
    </div>
</script>
<script id="cellTemplate" type="text/x-jQuery-tmpl">
    <div class="cell">
        <span>${id}</span> : <span>${name}</span>
    </div>
</script>

The line that calls the template is the following:

$("#rowTemplate").tmpl(arr).replaceAll("#somediv");

I am getting only one row with one cell with no data...

<div class="row">
    <div class="cell">
        <span></span> : <span></span>
    </div>
</div>

What am I doing wrong?

回答1:

I think the problem is with usage of replaceAll and the missing parameter to tmpl in the template. Try this(used replaceWith for #someDiv and passed $data as tmpl parameter for child template):

<script type="text/javascript">  
    var arr = 
    [
        [
            {
                    "id": 1,
                    "name": "one"
            },
            {
                    "id": 2,
                    "name": "two"
            },
            {
                    "id": 3,
                    "name": "three"
            }
        ],
        [
            {
                    "id": 4,
                    "name": "four"
            },
            {
                    "id": 5,
                    "name": "five"
            },
            {
                    "id": 6,
                    "name": "six"
            }
        ]
    ];

    $(function(){
         $("#somediv").replaceWith($("#rowTemplate").tmpl(arr)); 
    });
</script>    
<script id="rowTemplate" type="text/x-jQuery-tmpl">
            <div class="row">
                {{tmpl($data) "#cellTemplate"}}
            </div>
</script>
<script id="cellTemplate" type="text/x-jQuery-tmpl">
        <div class = "cell"><span>${id}</span>:<span>${name}</span></div>
</script>   
<div id="somediv"></div>