pre-compiling jsrender templates

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.

Answers:

Answer

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/

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.