Search code examples
javascriptbackbone.jsunderscore.js-templating

Passing data to view template is undefined in Backbone.js?


All,

I am trying to pass a simple JSON object for the time being (tried with a model but still the same problem).

I have initialised my View as such with a variable called "skills" which I want to pass into my template. However inside the template it is saying it is undefined.

    define([
    'jquery',
    'underscore',
    'backbone',
    'text!templates/skillsPopup.html', //for templates you should prepend the path with !text
    'common'
], function ($, _, Backbone, SkillsTemplate, Common, Skills)
{
    'use strict';

    var FilterView = Backbone.View.extend({

        el: $("#skillsPopup"), //set this to the element where the template will be rendered upon

        skills : 
            [{
                "skillCode": "Mechanical Engineer",
                "skillDescription": "Mechanical Engineer"
            },
            {
                "skillCode": "Air Conditioning Engineer",
                "skillDescription": "Air Conditioning Engineer"
            },
            {
                "skillCode": "Electrical Engineer",
                "skillDescription": "Electrical Engineer"
            }],



        template: _.template(SkillsTemplate),

        // setup the view to listen to its counterpart model for changes
        initialize: function ()
        {
            this.render();
        },

        // render template onto the view
        render: function ()
        {
            this.$el.html(this.skills);
            return this;
        }
    });

    return FilterView;
});

Template

<div id="test">
      <% console.log(skills); %>
</div> 

Error

ReferenceError: skills is not defined

console.log(skills);

I have looked at several Backbone tutorials and I can't see any mistake I am making.


Solution

  • You should be passing a context to your template, not to jQuery's html method:

    this.$el.html(this.template({ skills: this.skills }));