1

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

I'm trying to use a JSON string to output to an underscore template:

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

var $furnitureList = renderFurniture();

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

But it is just outputting "Result".

What am I doing wrong here? Is the JSON formatted correctly? Thank you!

and the HTML and template:

<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>
HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154

1 Answers1

1

you need to parse the JSON, using $.parseJSON or JSON.parse

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

fiddle

Austin Greco
  • 32,997
  • 6
  • 55
  • 59
  • Do note that using `JSON.parse` [might not work correctly](http://stackoverflow.com/questions/7051500/json-parse-error-on-internet-explorer) in *certain* browsers :) – summea May 01 '13 at 21:53