Store a jsRender template in a separate js file
是否可以将jsRender模板存储在单独的文件中?
我想将其存储在单独的文件中,并在页面中对其进行引用。
像这样的东西
1 | <script id="templateName" type="text/x-jsrender" src="thisIsTheTemplate.js"> |
我将不胜感激任何建议或建议。
谢谢
是的,您可以完成此操作(我每次都使用此功能)。
假设您的模板位于
在页面中,您使用jQuery
1 2 3 4 5 6 7 8 9 | 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)); }); } |
然后传递一个对象
1 | renderExternalTmpl({ name: 'productDetails', selector: '#items', data: {} }) |
您可以拥有一个不错的实用程序类来保存所有这些内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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 }; }); |
您可以轻松地致电
这是我编写的一次加载一个或多个外部模板的函数。它还缓存模板,因此如果模板已经加载,则不会再次加载。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function loadTemplates() { var toLoad = [], loadAll = $.Deferred(); $.each(arguments, function(i, templateName) { var filepath = '/path/to/templates/' + templateName + '.html', loadTemplate = $.Deferred(); toLoad.push(loadTemplate); if ($.templates[templateName]) { loadTemplate.resolve(); } else { $.get(filepath , function(html) { var newTemplate = {}; newTemplate[templateName] = html; $.templates(newTemplate); }).fail(function() { throw 'Could not load template at '+filepath; }).done(function() { loadTemplate.resolve(); }); } }) $.when.apply($, toLoad).done(function() { loadAll.resolve(); }); return loadAll; } |
像这样使用它:
1 2 3 4 5 6 7 8 9 10 | loadTemplates('modal','itemDetail', 'itemsList').done(function() { // do stuff when all templates are loaded $('#viewItemDetail').on('click',function() { $.render.itemDetail({ id:'123', name:'Cool Thing', description:'This thing is really cool.' }); }); }); |
我最近自己遇到了这个问题。在浏览完jsRender代码并研究了其他javascript库之后,我决定编写自己的库,该库将简化外部模板的加载,从而使人们可以使用
https://github.com/stevenmhunt/tmpl.loader
该库与jsRender以及任何能够处理模板的代码一起使用。
请享用!
如果像我以前那样试图从本地文件加载外部模板,请让我省些麻烦。
不要按照balexandre的答案中的建议使用jQuery
使用
有关详细信息,请参见我通过AJAX加载jsrender模板时对错误的回答。
根据我的经验,您无需解决该麻烦,只需要在使用模板之前将模板附加到页面即可。参见下面的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | var file = '/tmpl/all.tmpl.html'; $.ajax({ url: file, async: false, type :"GET", dataType: 'text', cache: true, success: function(contents) { $("#all_template").append(contents);//append all your template to the div } }); var data = {}; $('#js-template').render(data);//use it as the same old way |
这样,您不需要每次想要呈现js模板时都请求ajax文件