Note that there are some explanatory texts on larger screens.

plurals
  1. POHandling undefined attributes in underscore.js templates
    primarykey
    data
    text
    <p>I am rendering a single Backbone model in a view. I am using the default underscore template to render the model. How do I handle the "undefined" attribute errors when I am rendering the view (though the model has not loaded)? To clarify, here is an example.</p> <pre><code>// Using Mustache style markers _.templateSettings = { interpolate : /\{\{(.+?)\}\}/g }; App.Model = Backbone.Model.extend({}); App.Collection = Backbone.Collection.extend({ model: App.Model }); App.View = Backbone.View.extend({ initialize: function() { _.bindAll(this, 'render'); this.template = _.template($('#model_template').html()); this.model.bind('reset', this.render); }, render: function() { var renderedContent = this.template(this.model.toJSON()); $(this.el).html(renderedContent); return this; } }); // HTML &lt;div id="container"&gt;&lt;/div&gt; &lt;script id="model_template" type="text/template"&gt; &lt;strong&gt;Name:&lt;/strong&gt; {{ name }} &lt;br/&gt; &lt;strong&gt;Email:&lt;/strong&gt; {{ email }} &lt;br/&gt; &lt;strong&gt;Phone:&lt;/strong&gt; {{ phone }} &lt;/script&gt; // Run code var collection = new App.Collection; var view = new App.View(model: collection.at(0)); $('#container').html(view.render().el); collection.fetch(); </code></pre> <p>When this code is run, the view is rendered twice, first with an empty model and second when the AJAX query is complete (and 'reset' is triggered). But the issue I am facing is JS stops at the first instance when the model is empty. It gives an error saying the model attribute is undefined.</p> <p>What am I doing wrong here? Can I suppress the 'undefined' error when the view is rendered in the first instance?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload