Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return function value in lodash templates

I am using lodash templates to render html templates client side. There are many html templates which are being repeated. So, I decided to call the repeating template in another template. For example:

dummy.html

<%= _.template(templates['button'])({ title: "click me" }) %>

The above approach works but as I am calling _.template to render a button again and again, I thought to make a global function as shown below:

dummy.js

var sb = {
    setButton: function(data){
        data = data || {};
        return _.template(templates['button'])(data);
    },
    /* other functions */
}

and then call in the dummy.html as:

<%= sb.setButton({ title: "click me" }) %>

But this isn't working. (It just doesn't render)

What I am doing wrong here?

EDIT:

I placed console.log(this) in setButton function. it was not logging anything in chrome console. Then I removed = from lodash template syntax, then it logged sb global variable.

<% sb.setButton({ title: "click me" }) %>

But still the above one is not rendering the button.

like image 740
Mr_Green Avatar asked Sep 27 '22 10:09

Mr_Green


1 Answers

Your compiled templates don't know what sb is. Assuming you're calling your main template with something like _.template(src)(), Lodash chokes on it with an error looking like ReferenceError: sb is not defined. Pass your partials hash as an option and you will get your button:

var templates = {
    button: '<button><%= title %></button>'
};
var sb = {
    setButton: function(data){
        data = data || {};
        return _.template(templates['button'])(data);
    }
};

var src = '<%= sb.setButton({ title: "click me" }) %>'
document.getElementById('result').innerHTML = _.template(src)({sb: sb});
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<div id='result'></div>

If you prefer to have you partials directly available without passing them to your template, attach your global to _, for example as _.sb:

var templates = {
    button: '<button><%= title %></button>'
};
_.sb = {
    setButton: function(data){
        data = data || {};
        return _.template(templates['button'])(data);
    }
};

var src = '<%= _.sb.setButton({ title: "click me" }) %>'
document.getElementById('result').innerHTML = _.template(src)();
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>
<div id='result'></div>
like image 60
nikoshr Avatar answered Oct 28 '22 20:10

nikoshr