0

我已经准备好 html 标记,这不会改变,我只想在这个标记中添加/更新变量。

我如何使用主干和下划线来做到这一点?

我尝试了以下方法,

骨干:

testView = Backbone.View.extend({
    initialize: function(){
        this.render();
    },

    render: function(){
        var variables = {reqNumber: 10};
        /*This is where I'm having problems, how do I use only variables in my template??
        * How do I write this next line
        */
        var template = _.template(this.$el.html(), variables);

        this.$el.html(template);
    }
});

var test_view = new testView({ el: $("div.container") });

HTML:

<a href="#">
    <i class="icon-home icon-white"></i> 
    Requests <span class="badge badge-warning"><%= reqNumber %></span>
</a>
4

1 回答 1

0

像这样的东西有效。问题是,您没有确定模板在哪里 this.$el 指向视图的容器,而不是模板(请参阅模板脚本)。

JS:

$(function() {
    var testView = Backbone.View.extend({
        initialize: function(){
            this.render();
    },
    render: function(){
        var variables = {'reqNumber': '10'};
        var template = _.template($('#test-templ').html(), variables);

        this.$el.html(template);
   }
   var test_view = new testView({ el: $("div.container") });});
});

HTML:

<script id="test-templ" type="text/html">
    <a href="#">
        <i class="icon-home icon-white"></i> 
        Requests <span class="badge badge-warning"><%= reqNumber %></span>
    </a>
</script>   
<div class="container"></div>
于 2013-01-16T04:47:08.487 回答