Call a function inside an underscore template using backbone
14,445
Solution 1
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() %>
Solution 2
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') %>
Related videos on Youtube
Author by
Admin
Updated on September 15, 2022Comments
-
Admin over 1 year
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 !
-
TYRONEMICHAEL over 10 yearsKeep your templates dry. Your templates should not contain any logic.
-
-
Admin over 10 yearsYes you are right, I thought of it. I would like callFunction() to be a call of jPlayer (a jquery media player), which needs a source (url.mp3). The source's url is in my output. A little tricky isn't it ?
-
Ako over 4 yearsJust to note, it is Lodash feature, Underscore 1.9.1 does not have it.