pre-compiling jsrender templates

烂漫一生 提交于 2019-12-08 04:54:52

问题


I have a couple of jsRender templates that are used on all pages. Instead of using the script tag method, I would prefer to precompile them and put resulting functions in an external js file.

I saw a previous question that asked this but the method described doesn't seem to work anymore or I am doing something wrong.

I called $.templates("#myTemplate") from the console which msanjay suggested and copied/renamed the anonymous function and get something like this (which looks a bit odd to my untrained eye):

function myTemplate(data, view, j, b, u) {
    var j = j || jQuery.views, h = j.converters.html, ret; try {

        return "<div...";

    } catch (e) { return j._err(e); }
}

If I then try and use this template by calling var html = $.render( data, myTemplate ); I get an error:

Uncaught TypeError: Property 'render' of object function (a,b){return new p.fn.init(a,b,c)} is not a function

Not sure if the jsRender has changed and this is no longer possible or if I am doing something wrong, but any guidance would be highly appreciated.


回答1:


Last update has a lot of API changes. Looks like $.render now is just empty object.

Look at this page Provide a tool for pre-compiling templates and you will find this demos: JsRender: Variants and Details

For example you can try this:

var movies = [
    { name: "The Red Violin", releaseYear: "1998" },
    { name: "Eyes Wide Shut", releaseYear: "1999" },
    { name: "The Inheritance", releaseYear: "1976" }
];

var myTemplate = $.templates( "<div>{{:#index+1}}: <b>{{>name}}</b> ({{>releaseYear}})</div>" );
$("#movieList").html(myTemplate.render( movies));

Demo: http://jsfiddle.net/76nMC/




回答2:


You might get what you want by compiling templates from strings. In brief, it looks like this:

$.templates({
    myTemplateName: " blah blah {{>something}} blah "
});

var tempHtml = $.render.myTemplateName(myData);

I realize you may be stuck on the notion of having precompiled templates on the notion that it will save you some execution time, but in my experience jsrender is so fast I never notice it.



来源:https://stackoverflow.com/questions/13103131/pre-compiling-jsrender-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!