Is it possible to store a jsRender template in a separate file?
I want to store it in a separate file and make a reference of it in my page.
something like this
<script id="templateName" type="text/x-jsrender" src="thisIsTheTemplate.js"></script>
I will apreciate any commemnts or suggestions.
Thanks
Yes, you can accomplish this (I use this every time).
let's assume that you have your templates in a template
folder and it is called, for example _productDetails.tmpl.html
in your page you use jQuery $.get()
to pull it and load into the template, like:
var renderExternalTmpl = function(item) {
var file = '../templates/_' + item.name + '.tmpl.html';
$.when($.get(file))
.done(function(tmplData) {
$.templates({ tmpl: tmplData });
$(item.selector).html($.render.tmpl(item.data));
});
}
and you pass an object item
witch will contain all 3 properties, like:
renderExternalTmpl({ name: 'productDetails', selector: '#items', data: {} })
You can have a nice utilities class to hold all this:
var my = my || {};
my.utils = (function() {
var getPath = function(name) {
return '../templates/_' + name + '.tmpl.html';
},
renderExtTemplate = function(item) {
var file = getPath( item.name );
$.when($.get(file))
.done(function(tmplData) {
$.templates({ tmpl: tmplData });
$(item.selector).html($.render.tmpl(item.data));
});
};
return {
getPath: getPath,
renderExtTemplate: renderExtTemplate
};
});
and you can easily call my.utils.renderExtTemplate(item);