ptheofan
ptheofan

Reputation: 2290

backbone view with underscore template how to avoid wrapping the template in the view.tag element

Typically in backbone/underscore templates we have the template

<script type="text/template" id="something">
    <%=value%>
</script>

when we instantiate it in a view we get the content wrapped in an element. So the following statement

template: _.template($('#something').html()),

will produce a markup like

<div>MyValueHere</div>

What I would like to do is to specify that wrapping element in the template i.e.

<script type="text/template" id="something">
    <div>
       <%=value%>
    </div>
</script>

so when calling

template: _.template($('#something').html()),

the result I would like to have is

<div>
    MyValueHere
</div>

and not the following (which is the result of wrapping the template in the tag found in the view of backbone)

<div>
    <div>
        MyValueHere
    </div>
</div>

Any ideas how to do that efficiently? Would really appreciate a jsFiddle if it's not too much trouble.

Upvotes: 0

Views: 124

Answers (1)

mu is too short
mu is too short

Reputation: 434785

The usual pattern in render looks like this:

render: function() {
    this.$el.append(this.template(...));
    return this;
}

but you could replace the usual append call with a setElement call to replace the view's el with one of your own:

render: function() {
    this.setElement(this.template(...));
    return this;
}

Demo: http://jsfiddle.net/ambiguous/t977y/

You'll still have a <div> created in this.el before your setElement call but that probably doesn't matter that much.

Upvotes: 1

Related Questions