Rectangle 27 0

{{#each Languages}}
                 {{=$ctx.format(Name, "upper")}}{{#if $ctx.nextToLast($view)}} and {{else $ctx.notLast($view)}}, {{/if}}

Thanks Anderson. That was it. Not sure i 100% understand the syntax '$ctx.' & '$.views.registerHelpers' but it seems to work. Hopefully as it because more mature i will find the answer :).

In the recent beta candidate, the syntax is a lot simpler: ~format(...). Here is an example:

How to call a javascript function for an external jsRender Template (f...

javascript jsrender
Rectangle 27 0

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

    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.

javascript - pre-compiling jsrender templates - Stack Overflow

javascript jquery jsrender
Rectangle 27 0

Update: I thought I'd come back and update this to let people know that we settled on Handlebars.js. We've got several months experience with it under our collective belts and we've been very happy with our choice. It has the basics included and you can create helpers that give you additional capabilities as needed.

We've been doing a survey of JavaScript template engines because there are so many and they have many different syntax and performance profiles (some compiled, some not, etc.).

Unfortunately our favorite solution was jQuery Templates and it worked great. Now it's deprecated software and the proposed replacement for it (JsRender) is no where near ready to use at the time I write this (Oct 2011). So while there are so many to choose from, after having a solution we were quite happy with, we are suddenly adrift again and trying to find its replacement.

Current state of JavaScript template engines? - Stack Overflow

javascript templates template-engine jsrender
Rectangle 27 0

<ul id="output"></ul>
<script id="template" type="text/x-jsrender">
    <li>{{:name}} likes to wear {{:shirtColor}} shirts</li>

Must work. Because when you render a template with a array object, he render n times the same template.

javascript - How can I iterate over a JSON array in a jsRender templat...

javascript jsrender
Rectangle 27 0

  • The toggleButton was being referred to in jQuery without the #. So I added that.List item, otherwise the click was not being captured.
  • Your fiddle did not reference jQuery nor JsRender, though you were using both, so I added them. (I assume you never ran the fiddle)

I passed showInvisible to the inner for loop using a parameter, so it could be accessed in its context.

{{for sections ~showIt=showInvisible}}

{{if (editorspick_amount > 0 || ~showIt)}}

The template you were trying to render did not exist, so I changed the rendering code to use the script tag you created. This also sets the allowCode=true, which is required to safely turn on the allowCode feature.

$.templates("myTmpl", {markup: "#datascapeTemplate", allowCode: true });

        rendered = true;
            $.render.myTmpl( datascape.json )

I changed one place where you used {{* }} to instead use an {{if}} block since there was no need to use allow code.

This allowed all of the code to run and the template to render, though I admittedly did not follow all of what you were trying to do.

One suggestion ... the allowCode feature makes for really ugly templates and hard to maintain and read. I highly recommend replacing it with helper functions (or other constructs). For example, you used allowCode to create the styling for some elements. You could have used a custom tag for this instead, and moved the logic to javascript and simplified your template. The colcounter could be moved to a helper function. It's just much more readable to move the logic to javascript, and keep the template/html clean. Just my 2 cents :)

Awesome! Thanks a lot for the detailed explanation, i was able to adapt your input to make it work - and learned in the process.

Glad I could help. I'd love to see your final code when you are done, if you could put it in a fiddle and share.

Hi John, i've published the new template here: But i'm having another issue: it works for some json files, not for others, so it's a bit unreliable. I'll update the fiddle to illustrate that.

No, in fact i think my issue is css-related, the jsfiddle works fine. You'll see i used helpers, as you advised.

javascript - define a variable inside a jsrender template - Stack Over...

javascript jquery jsrender
Rectangle 27 0

Answering in case anyone stumbles upon this. The problem was in fact the ajax call. Not sure exactly what it was but you cannot return the string from the success part of the ajax call. Modified the function as follows and works fine.

renderPrimaryResource: function (PrimaryResource, LessonID) {
        url: "cl/lb",
        dataType: "json",
        data: { id: PrimaryResource.ResourceID },
        type: 'GET',
        async: false,
        success: function (data) {
            var thumbnailImage = data[1];
    if(thumbnailImage != null){
        return thumbnailImage;

javascript - jsrender not displaying function return in template - Sta...

javascript jquery jsrender
Rectangle 27 0

Successfully tested with a fiddle. Your question is not formulated very clearly. What exactly does not work? In which context is your template? What data structure are you using?

var template = $.templates("#newsSingleTemplate");"#result", data);

javascript - jsrender template will not render, any ideas? - Stack Ove...

javascript jquery jsrender
Rectangle 27 0

As @Dhaivat Pandya suggested, template is a registered keyword. Thanks for the help!

javascript - jQuery/jsrender - Uncaught RangeError: Maximum call stack...

javascript jquery google-chrome jsrender
Rectangle 27 0

"PageContentList": [
        "ContentId": 44, 
        "Title": "Company Name", 
        "Gallery": {
            "Images": [
                    "Path": "", 
                    "MimeType": "image/jpeg", 
                    "ImageWidth": 0, 
                    "ImageHeight": 0, 
                    "AltText": null
            "Videos": [ ]
{{for PageContentList}}
<video id="whatIsSolutiaVideo" class="video-js vjs-default-skin" controls width="{{:Gallery.Images[0].ImageWidth}}" height="{{:Gallery.Images[0].ImageHeight}}" poster={{:Gallery.Images[0].Path}}" preload="auto">
{{for Gallery.Videos}}
<source type="{{:MimeType}}" src="{{:Path}}">

I know each JSON data will have a section for Images, Videos, etc. Now it becomes a data entry issue. If the data entry person did their job right, then there will be data. The approach I moved to ensures the correct data structure. Thanks for forcing me to think through this.

+1 Splitting videos and images into two different arrays makes your code less complex and that's always a good thing. A great solution.

javascript - with jsRender, how do you pull a specific item from array...

javascript json templates jsrender
Rectangle 27 0

While you could modify your data to carry your current row ID, it is generally as easy (and cleaner) to 'parameterize' the template, by passing in parameters with the render method. You can do that by passing in an additional context parameter. It can carry both parameters and helper functions that you can pass in dynamically just for this template rendering...

$("#my_template").render(myData, {currentRowId: myCurrIdVar}));

Then you can access those named parameters from within the template (or within nested templates, too) in the same way as you would access a registered helper - by appending '~' to the name.

{{if ENTRY_ID==~currentRowId}}

javascript - JsRender: using if statement comparing values in JSON obj...

javascript jsrender
Rectangle 27 0

I have achieve this requirement by using code snippet like below.

Correct - you can do that.

javascript - Arithmetic operator in jsRender Template - Stack Overflow

javascript jsrender
Rectangle 27 0

The main thing you missed that will help is to use observeAll:


I also added a couple of different approaches for other things:

<td><button data-link="{on ~remove}">Remove</button></td>

Top-level data-linking to show the length of the array:

<span id="getLength" data-link="length"></span>


$("#getLength").link(true, people);

That's awesome! Thanks a lot!

javascript - Summary Value Calculation with JsViews - Stack Overflow

javascript jquery-templates jsrender jsviews
Rectangle 27 0

The {{if ...}} block adds another view, so means you need to add a .parent to step up through that view, as in: {{}}

You can pass in variables as you said (~myproperty=...) and they will be visible to any depth of nesting.

Your variable can be an object too such as the current data object: ~myObj=#data:

{{sometag a=b ~myObj=#data}}

You can also access the top-level data object and drill down from there:


And finally you can use #get("item") to step up through any number of {{if}} blocks and get the nearest "item" view (i.e. the item view for a repeating {{for ...}} block).

So you would write:


javascript - JSrender: cannot access parent variable inside if conditi...

javascript jsrender
Rectangle 27 0

You have to use live to bind the event on input.

$("input").live('change',function() {
    var id = $(this).attr("id");
    var year = $(this).val();

    $( "#year-"+id ).html(year);

Actually, as of jQuery 1.7 you should be using on() instead of live().

javascript - Updateable jsRender template - Stack Overflow

javascript jquery jquery-templates jsrender
Rectangle 27 0

An important difference between JsRender and jQuery Templates is that JsRender does not let you access global functions or variables directly within template markup.

This is a design choice, related to security concerns, and separation of concerns. But unlike "logicless" template languages, such as Mustache, JsRender provides very powerful and flexible support for logic within the template - while still preventing random mixing of code and markup.

One way to include logic is to encapsulate it outside the template in helper functions, but in that case you need to register the helper function, either globally, or for the specific template, or else pass it in on an options object with the render call.

So in your case you can do

function filterOutMainImages(images) { ... }

var html = $("#largeTemplate").render(
    {filterImages: filterOutMainImages} // Pass in helper


Assuming your filterOutMainImages() function returns a filtered array, and with your helper registered or passed in as above, then the following templates should work:

<script id = "imagesTemplate" type="text/x-jsrender">    
    <img src="{{>imgUrl}}" />

<script id = "largeTemplate" type="text/x-jsrender">
    {{for ~filterImages(Images) tmpl="#imagesTemplate"/}}

Actually Boris if you look at my test page it still seems to not be working. Is it the way I am writing the array? It actually looks like it may be the way I am trying to call each item in the loop. there does not seem to be an "handle EACH as..." I have written out a commented line in the top of the #LARGE div that shows the array is getting to the for loop.

got it just used as if it were array[i]in a for loop or each as in an each loop. So in your above example {{>imgUrl}} should be {{}}

Well if your function returns an array of strings, it would be {{:#data}} - which is shorthand for {{}}. Or you can encode using {{>#data}}, {{attr:#data} or {{url:#data}} - see I had assumed you returned an array of objects with imgUrl properties, given your previous versions.

wow awesome sophistication of your library! Nice to have those options, great job. Thanks again.

javascript - Trying to run a function on an array in a, for loop, usin...

javascript templates jquery-templates jsrender
Rectangle 27 0

$(document).on("click", '.delete', function () {
    //do stuff

$(document).on("click", '.editRight', function () {
    //do stuff

javascript - Bind events inside jsrender template - Stack Overflow

javascript jquery ajax jsrender
Rectangle 27 0

When you tried the version with two if statements, did you remember to add a {{/if}} in addition to changing the {{else}} into an {{if}}?

{{if type eq='photo'}}
    <img src="{{:src}}" />
    <div class="photo-caption">
{{if type eq='quote'}}
    <div class="quote-text">

Yes. Otherwise I would have gotten an error in the console.

@wtfsven: well, thats pretty weird then. Maybe you should try creating a small executable JSFiddle reproducing your problem.

javascript - JsRender if-else renders nothing - Stack Overflow

javascript templates jsrender
Rectangle 27 0

Note that the browser does not interpret scripts with type="text/x-jsrender" and therefore Firebug (or the built-in DevTools debugger) doesn't display the contents of the <script> tag.

Also note that JsRender templates are not JavaScript, so they cannot be debugged with JavaScript debuggers. It is JsRender that uses the type text/x-jsrender as indicator that it needs to parse the contents within the <script> tag.

You will be able to see the contents of the tags within Firebug's HTML panel, though.

I dont want to debug jsrender i am mentioning jsrender because i am using it in my app and i think current version of firefox is super sensitive to that . I want to debug my plain javascript and i dont have jsrender in my current page iam developing such pages were getting debugged fine before the last update of firefox

after the last update some times the debugger does not display the javascript but displays it after restart

Ok, if your problem is not related to JsRender, you should clarify that in your question. So when it's about plain JavaScript, this seems to be a bug, which is filed as issue #7918.

Something looks to be fixed in Firefox 40. So you may want to either use Firefox 38 ESR or Firefox 40 (currently beta). See

In Firefox 40 the bug does not appear, though in Firefox 41 it's back again - at least when you just reload the page.

debugging - Why does Firebug just display JavaScript after restarting ...

javascript debugging firefox firebug
Rectangle 27 0

I'm using jsRender + Jurassic to precompile my templates and generate js-files in T4. I spent a lot of time solving this problem and didn't find the answer, but read some articles, that helped.

See my code. It's working in my case. I'm sure I can help you to solve the issue, if this will not help:

var engine = new Jurassic.ScriptEngine();

var jsRenderPath = "/pathToDir/jsrender.js";
var jsUnevalPath = "/pathToDir/jsRenderUtils.js";

engine.Evaluate("function renderTemplate(name, markup) { var tmpl = this.jsviews.templates(name, markup); return uneval(tmpl); }");

var compiledTemplateString = engine.CallGlobalFunction<string>("renderTemplate", templateName, templateString);

var result = "$.templates['" + templateName + "'] = " + compiledTemplateString + ";";
function uneval(obj, known) {
    var root = (known === undefined), result;
    known = known || [];

    // some values fail eval() if not wrapped in a ( ) parenthesises
    var wrapRoot = function (result) {
        return root ? ("(" + result + ")") : result;

    // special objects
    if (obj === null)
        return "null";
    if (obj === undefined)
        return "undefined";
    if (obj !== obj) // isNaN does type coercion, so can't use that.
        return "NaN";
    if (obj === Infinity)
        return "Infinity";
    if (obj === -Infinity)
        return "-Infinity";

    // atoms
    switch (typeof obj) {
        case 'function':
            return wrapRoot(obj.toString());
        case 'number':
        case 'boolean':
            return obj.toString();
        case 'string':
            return "\"" + obj.toString() + "\"";

    // circular reference check for non-atoms
    if (known.indexOf(obj) !== -1)
        return "null";//throw new Error("Circular references detected while unevaling.");


    // specialized types
    if (obj instanceof Array)
        return "[" + (o) { return uneval(o, known); }).join(",") + "]";

    if (obj instanceof Date)
        return wrapRoot("new Date('" + obj.toString() + "')");

    // hashes
    var key, pairs = [];
    for (key in obj) {
        var val;
        switch (key) {
            case "render":
                val = "$.fn.render";
            case "markup":
                val = "null";
                val = uneval(obj[key], known);
        pairs.push("\r\n" + key + " : " + val);

    return wrapRoot("{" + pairs.join(",") + "}");

$ = window.jsviews;
$.fn = {
    render: function (data, view, j, u) {
        return this.fn(data, view, j, u);
testJSTemplate: ({ 	markup : null, 	tmpls : [], 	links : {}, 	tags : {}, 	bnds : [], 	_is : "template", 	render : $.fn.render, 	tmplName : "testJSTemplate", 	htmlTag : "li", 	fn : function anonymous(data, view, j, u) { 		// testJSTemplate 		var j=j||jsviews,v,ret=""; 		try{ 			ret+="<li>"; 			ret+=(v=data.Name)!=u?v:""; 			ret+="</li>"; 			return ret; 		}catch(e){ 			return j._err(e); 		} 	} })

Does that look correct to you? I can't quite check by myself because I'm encountering other problems with using the template, but didn't want to leave it too long before responding to your answer.

@awj Yes, it is correct. Important notice. You should use $.templates['" + templateName + "'] to be able to use nested templates (include and for) I created jsfiddle and found out, that without jquery you have to define $ and $.fn.render. PLease, check it out:

You are welcome!) I'm happy that's my research on this helped somebody else besides me.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - Using Jurassic to precompile a JsRender template server-s...

javascript templates jsrender jurassic precompiled-templates
Rectangle 27 0

You can use {{for}} to iterate over an array. Something like this:

{{for columnName}}

Inside the loop, your base scope automatically becomes that particular object in the array, so you can output any of the object's properties directly with {{:Property}}.

javascript - for loop with in the jsrender template - Stack Overflow

javascript jquery html jsrender