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:
<%= _.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:
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With