Friend, the best thing to do is automate the precompile process, if you'd like to know how to do it using Grunt, you can read more about this at link ;
You can also retrieve the 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 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 only 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><textareaid="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>