Call a function inside an underscore template usin

2019-02-16 09:28发布

Just a thing I try to do that would really simplify my life right now.

How can I do that :

This is my view in app file

    window.ArtView = Backbone.View.extend({
        template:_.template($('#art').html()),
        render:function (eventName) {
            var output="blablbla";
            $(this.el).html(this.template({"output":output}));
            return this;
        }
    });
    ...
    // function that I would like to call
    function callFunction(){
        console.log('it works!');
    }

Template in index.html

<script type="text/tempate" id="art">
        <div data-role="header" class="header" data-position="fixed">
            <a href="#" data-icon="back" class="back ui-btn-left">Back</a>
        </div>
        <div data-role="content" class="content">
            callFunction();
            <% console.log(output) %>
        </div>
</script>

How can I call callFunction() inside my template or something alike ?

Any idea ?

Thanks !

3条回答
The star\"
2楼-- · 2019-02-16 10:03

I believe you can call functions within the template as long as the object for the template has the function.

render:function (eventName) {
    var output="blablbla";
    var data = _.extend({"output":output}, callFunction);
    $(this.el).html(this.template(data));
    return this;
}

then in your template:

<%= callFunction() %>
查看更多
闹够了就滚
3楼-- · 2019-02-16 10:04

That's wrong. Think about the template as a string, html markup. You get it and replace some parts of it with the actual data. If you want to do some DOM manipulation they should be made after that. Let us know what you want to do in callFunction and we may guide you to the right place for that logic.

查看更多
成全新的幸福
4楼-- · 2019-02-16 10:25

this is how I did it , it works fine.

template: _.template(templateText , {
            imports : {
                check :function (val){
                    // blah blah
                    }
                }
            }
        }),

then in your html template

<%= check('value') %>
查看更多
登录 后发表回答