0
votes

I use Browserify to load a Backbone View. The view is rendering some html templates with underscore. The "tmpl2" method is generating an empty string when i load the template markup from the html template script. Are there any issues between browserify and underscore or why its rendering an empty string? (I use latest version of browserify, underscore, backbone, jquery)

View.js:

var $ = require('jquery');
var Backbone = require('backbone');
var _ = require('underscore');
Backbone.$ = $;

var View = Backbone.View.extend({

    tmpl1: _.template("<p>hello: <%= name %></p>"),     //HTML hardcoded
    tmpl2: _.template( $.trim( $('#tmpl').html() ) ),     //HTML from template

    render: function(){
        console.log( $.trim( $('#tmpl').html() ) );   //<p>hello: <%= name %></p> <-- OK
        console.log( this.tmpl1({name : 'moe'}) );      //<p>hello: moe</p>         <-- OK
        console.log( this.tmpl2({name : 'moe'}) );      //(Emptystring)             <-- WTF ???
    }

});

module.exports = View;

index.html:

<script type="text/template" id="tmpl">
    <p>hello: <%= name %></p>
</script>
1
Are you sure the DOM is loaded at the point that your compiling your template?Jack
yes, the dom is already loaded, the script for loading and rendering this backbone view is inside an jquery ready method "$(function(){})".htmlcoder
Is that the code for instantiating the view, or declaring it? I suspect that it is the later and that is the issue.Jack
yes you are absolutely right, now i see that i have placed the require method in the main.js, for loading this view, outside the jquery ready function. when calling require('view.js') inside the ready method, it will parse template correctly, thanks for the right hint :)htmlcoder
Your welcome, glad to help. In general you can indicate that your question has a solution but ticking the check-mark to the left of the answer.Jack

1 Answers

0
votes

Your issue is most likely that at the point where your compiling your template the DOM hasn't loaded. While your render function is presumably not called until later which is why at the point your able to log the template.

When you declare a backbone view, the statements that assign a value to it's prototype are executed right away.

For example in your case the following line is executed right away

tmpl2: _.template( $.trim( $('#tmpl').html() ) ),     //HTML from template

You can instead compile the template in your initialize function (assuming that that is called after the DOM has loaded).

For example

initialize: function () {
  this.tmpl1 = _.template("<p>hello: <%= name %></p>");   //HTML hardcoded
  this.tmpl2 = _.template( $.trim( $('#tmpl').html() ) );
}

However this has the disadvantage of the template being compiled for every instance of your view, what would probably make more sense in your case is to store your template separately and require it and use that.