Search code examples
javascriptjquerybackbone.jsunderscore.jsunderscore.js-templating

Underscore.js: Uncaught ReferenceError: data is not defined


I'm trying to load a list of objects into a template using the Underscore.js forEach method:

HTML template code:

<script type="text/template" id="element">
    <% _.each(data, function (element) { %>
        <div class="col-xs-12 col-sm-12 col-md-4" id="inner-element">
            <div class="thumbnail">
                <img class="img-responsive" src="../../../img/<%= element.img %>" alt="...">
                <div class="caption">
                    <h3 class="menu-food-name"><%= element.name %></h3>
                    <p class="menu-food-description"><%= element.description %></p>
                    <p class="menu-food-price text-right"><span class="label label-info" role="button"><%= element.price %></span></p>
                </div>
            </div>
        </div>
    <% }); %>
</script>

Javascript:

var elementTemplate = _.template($('#element').html(), {data: item});
that.$el.append(elementTemplate);

"item" is defined prior as an object array containing three elements with properties (name, description, price, and img) I want to display in the template (as shown in console.log(item)):

Object {0: Object, 1: Object, 2: Object}
    0: Object
        description: "grilled portobello and balsamic"
        img: ""
        name: "fungi grigliati"
        price: "7.95"
        __proto__: Object
    1: Object
        description: "baked clams"
        img: ""
        name: "vongole oreganate"
        price: "7.95"
        __proto__: Object
    2: Object
        description: "mussels marinara sauce"
        img: ""
        name: "padellata di cozze"
        price: "13.95"
        __proto__: Object
__proto__: Object

I keep getting an "Uncaught ReferenceError: data is not defined" error in the dev console when I try to run this code. I think I might be overlooking the functionality behind how the Underscore forEach method works. I'm assuming maybe the data I'm passing through is not formatted correctly. Any ideas/help on this would be great.


Solution

  • The error is right there, data is not defined. This has nothing to do with _.each; rather, you are using _.template incorrectly.

    The second argument is templateSettings, not the data. You pass the data to the function returned by _.template.

    // create template function
    var elementTemplate = _.template($('#element').html());
    // render the template with the given data
    that.$el.append(elementTemplate({data: item}));