使用_.template将JSON字符串转换为下划线模板

时间:2013-05-01 21:41:27

标签: javascript jquery json backbone.js underscore.js

http://jsfiddle.net/rBhfx/6/

我正在尝试使用JSON字符串输出到下划线模板:

var renderFurniture = function() {
    var list = $('#list-json').text(),
        template = _.template( $('#furniture-template').html() ),
        compiled = template(list);
        return compiled;
}

var $furnitureList = renderFurniture();

$('body').append($furnitureList);

但它只是输出“结果”。

我在这里做错了什么? JSON格式正确吗?谢谢!

以及HTML和模板:

<div id="list-json">   
{
    "name": "Chair",
    "title": "Chairs",
    "items": [
        {
            "name": "Recliner",
            "title": "Recliner Chair",
            "type": "Chair",
            "quantity": "1"
        },
        {
            "name": "Club/Armchair",
            "title": "Club/Armchair",
            "type": "Chair",
            "quantity": 1
        }
    ]
}
</div>

<div class="accordion fl" id="items-index">
    <div class="accordion-group">
    </div>
</div>



<!-- Template -->
<script type="text/html" id="furniture-template">
    <div class="accordion-heading">
        <a class="accordion-toggle" data-toggle="collapse" href="#items-group1">
            <%= name %>
        </a>
    </div> <!-- header -->
</script>

1 个答案:

答案 0 :(得分:1)

您需要使用$.parseJSONJSON.parse

解析JSON
var renderFurniture = function() {
    var list = $('#list-json').text(),
        template = _.template( $('#furniture-template').html() ),
        compiled = template( $.parseJSON(list) );
        return compiled;
}   

fiddle