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
I recently ran into this problem myself. After looking through the jsRender code, and studying other javascript libraries, I decided to write my own library that would simplify loading external templates so that one could attach templates to a html page using the <link>
tag and render them by simply including the .js file. If you would like to check it out, I have posted the code on github with examples:
https://github.com/stevenmhunt/tmpl.loader
This library works with jsRender, as well as any code capable of processing a template.
Enjoy!
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);
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