ONYX
ONYX

Reputation: 5859

How to use custom functions within a Underscore template?

I have a helper JavaScript file but I can't use it in my template: it throws an error saying that the helper is not defined.

Example code:

<img alt="" src="<%= helper.isURL(images[i].small) ? images[i].small : '/img/' + images[i].small %>">

I tried embedding some raw javascript block with isURL but I still get the same error.

<script>function isURL() {}</script>

Upvotes: 0

Views: 1302

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

Underscore templates can use plain JS. You can expose anything you want in the context object that the compiled template function uses.

In the following example, I created a simplified Helper object which is passed to the compiled template function in the extended data object.

var data = { test: "value" },

    // simplified mock of the helpers
    Helper = { isUrl: function(){ return true; } },
    
    // compiled template function
    template = _.template('result: <%= Helper.isUrl(data.test) ? data.test : "default" %>'),
    
    // the same data, now including the Helper
    extendedData = _.extend({ Helper: Helper }, data),
    
    // rendered template as a string
    rendered = template(extendedData);

console.log(rendered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Anything public is also available by default.

Here, I use a public variable and the join Array's prototype function.

window.test = "public data";

var data = { arr: ['test', 'test2'] },
    template = _.template('arr: <%= arr.join(", ") %>\ntest: <%= test %>');

console.log(template(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>

Upvotes: 2

Related Questions