Question:
I usually use Template Engines to be able to render HTML via JavaScript. I commonly use undescore.js
.
I really like this way to make creating HTML with Templates easier.
Example:
Somewhere in HTML:
<script type="text/template" id="tpl-template">
Meu nome é <b><%= nome %>
</script>
In the JS file
var tplTemplate = _.template($('#tpl-template').html());
$('body').append(tplTemplate({nome: 'Wallace'}));
However, it is always necessary to leave this code with the HTML code. I wish I could organize these codes in a separate file (like a tpl.js
), for example, but I still haven't tpl.js
a way.
I believe that through the src
attribute there is no way to do this – if there is, correct me.
I need to know if there is any way to do this in JavaScript.
Answer:
Friend, the best thing to do is to automate the pre-compilation process, if you want to know how to do it using Grunt, you can read more about it in this link ;
you can also get the retrieve script from the script by accessing the source property through the source property, for example, if you do this:
console.log(_.template($('#tpl-template').html()).source)
you will possibly have the following output:
function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+=' Meu nome é <b>'+
((__t=( nome ))==null?'':__t)+
'</b>\n';
}
return __p;
}
so basically you would just need to have the following code in a separate JS file:
var templates = {};
templates.meuNome = function(obj){
var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
with(obj||{}){
__p+=' Meu nome é <b>'+
((__t=( nome ))==null?'':__t)+
'</b>\n';
}
return __p;
}
in your main script, you would just have to use templates.meuNome({nome: 'Wallace'})
, without the need to have the script#tpl-template
tag on the page.
finally a small example with a utility to generate the scripts:
var textTemplate = document.getElementById("textTemplate");
var textPreCompiled = document.getElementById("textPreCompiled");
var txtNomeTemplate = document.getElementById("txtNomeTemplate");
var btPrecompilar = document.getElementById("btPrecompilar");
btPrecompilar.addEventListener("click", function (event) {
var tmplSource = textTemplate.value;
var template = _.template(tmplSource);
textPreCompiled.value = "var " + txtNomeTemplate.value + " = " + template.source;
});
textarea {
width: 100%;
height: 240px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<textarea id="textTemplate">
Meu nome é <b><%= nome %></b>
</textarea>
<label>
Nome template:
<input id="txtNomeTemplate" type="text" value="tplTemplate" />
</label>
<input id="btPrecompilar" type="button" value="PreCompilar Template" />
<textarea id="textPreCompiled">
</textarea>
<script type="text/template" id="tmplNome">
</script>