0

I am looking at javascript code of an app built by using Backbone.js

there I find a function

render: function () {
        var that = this,
            template = _.template($(that.templateId).html(), that.model.attributes);

    }

and Here templateId:"#abc"

I am just trying to understand about the structure of _.template() function

Can anyone please help me out in understanding and how it is taking that.model.attributes as input

please pardon me if you need some more information.

1 Answer 1

2

As the manual said:

template

_.template(templateString, [data], [settings])

Compiles JavaScript templates into functions that can be evaluated for rendering.

...you can pass the data object as the second parameter to template in order to render immediately instead of returning a template function.

source: http://underscorejs.org/#template

So basically, _.template() take the html (template script) of the DOM element with id=abc defined somewhere in your DOM. Compile the data passed that.model.attributes and return the DOM part rendered and ready to be used.

In case you're not passing the second argument data you'll get a template function to be used then, i.e:

var rendered = template({whatever: that.model.attributes});

that.model.attributes so this.model.attributes so (pseudo) thisview.model.attributes refers to model binded to this view.

Anyway, I suggest you to read

Sign up to request clarification or add additional context in comments.

4 Comments

you said that it returns a function but I can see it return a variable name template like template = _.template($(that.templateId).html(), that.model.attributes); $("def").html(template);
I suppose the author has a more concrete idea than mine and yours. He wrote : Compiles JavaScript templates into functions that can be evaluated for rendering. So I suppose template = _.template($(that.templateId).html()... return a function that can be used then as template() for rendering DOM compiled.
By reading the manual however you can find all the answers. you can pass the data object as the second parameter to template in order to render immediately instead of returning a template function.
@AdonSmith: t = _.template(x) gives you a function in t, then you h = t(o) to get HTML in h, or you can h = _.template(x, o) to go straight to HTML without saving the intermediate function. Use the first form when you want to use the template more than once and the second form for one-offs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.