Search code examples
javascriptnode.jsbackbone.jspug

Send variable from backbone view to jade template


I have the following template in my index.jade:

....
<script type="text/template" id="sample-template">
  a(href="<%= link.href %>") <%= link.title %>
</script>
....

And I have the below code in my backbone view which sends a variable called link to index.jade.

....
var SampleView = Backbone.View.extend({
  template: _.template($('#sample-template').html()),

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

Now when I render that template I get the following output:

<a href="<%= link.href %>"> sample link

You see, I got the correct output for title variable. But the problem is with href. It doesn't print the value of link.href.


Solution

  • Finally I found out what is wrong with it. Because jade is a template engine that works with node (actually in server side), it has a lack of support in client side usage. So when you compile a jade template with underscore _.template function, you can't expect a functional template file. But there is an alternative way of sending variables from backbone view to jade template. You can create a helper function which print what ever you want in a jade template.

    ....
    var SampleView = Backbone.View.extend({
      template: _.template($('#sample-template').html()),
    
      render: function() {
        this.$el.append(this.template({
          link: this.model.toJSON(),
          ahref: this.ahref
      }));
      return this;
      },
    
      ahref: function( href, title ) {
        return '<a href=' + href + '>' + title + '</a>';
      }
    
    });
    ....
    

    Then I need to pass link helper function into the jade template.

    ....
    <script type="text/template" id="sample-template">
      ahref(link.href, link.title);
    </script>
    ....