Backbone.js view id tag using information from model

I am using backbone.js,

I have a model that is formatted like this:



I want to have the same view:

<div id="1">
    <span class="name">name<span>
    <img src="image.jpg" />


from this template:

<script type="text/template" id="users-template">
    <span class="name"><%= username %></span>
    <img src="<%= image %>" />      


but I got stuck when it came to putting the user id in the views id attribute.

UserView = Backbone.View.extend({

    id:, //this is what I have tried but it doesnt work

    initialize: function(){
        this.template = _.template($('#users-template').html());

    render: function(){


Does anyone know how to put the current model ID in the id attribute?


source to share

3 answers

First of all, your model has picture

, but your template uses image

, they must be the same or you will get a "missing variable" error from your template.

The attribute id

on the view must be the DOM of an id

existing element; Backbone won't add it to el

, Backbone uses it to find it el

. Also, this

it won't be displayed on run id:

( this

probably will window

or some other useless thing) and the property model

won't be set until the view is created anyway.

the view el


created from the idea tagName

, className

, id

and property attributes if they are specified. If not, el is empty div


So, leave id

in your view and use the default <div>

for el

. Then in your method, render

you can set the attribute id

to this.el

; Also, using a numeric attribute id

causes problems with some browsers, so you usually have to prefix it id

with something non-numeric:

render: function() { = 'v' + this.model.get('id');
    return this;



Open a console when you run the demo and you should be able to see the HTML that gets into your view this.el




I am using this

id : function () { 
    return this.model.get("id");


U can only get model data with ". Get ()"

Properties such as tagName, id, className, el and events can also be defined as a function if you want to wait to define them until runtime. @from



This is because the model is not set when JavaScript is initially executed. Try the following:

initialize: function(){ =;
    this.template = _.template($('#users-template').html());




All Articles