JsRender Deep Nested data templates

540 Views Asked by At

Is there a way to retrieve a template that is stored in a child object (AKA a child object stored in an array off of the parent object), when doing a for loop and apply that template on the child object?

I know that question is a bit confusing. Below is some code to make things clearer.

The following constructor functions represent my model:

function group (children) {
    this.children = children;
}
group.prototype.jsTmpl = $1_10_2.templates('<div class="group">{{for children tmpl=jsTmpl /}}</div>');
group.prototype.render = function(selector){
    $1_10_2(selector).html(this.jsTmpl.render(this));
}


function item (title) {
    this.title = title;
}
item.prototype.jsTmpl = $1_10_2.templates('<div class="item">{{:title}}</div>');

I am storing the unique jsRender template in the prototype of each object so I can easily access it when dealing with recursive data. Here I am newing up a 'group' object with four 'item' object children:

var vehicles = new group([
        new item('car'),
        new item('truck'),
        new item('van'),
        new item('bus'),
    ]);

Now when I call vehicles.render(); on my vehicles group instance I would expect the following:

Output: <div class="group">
            <div class="item">car</div>
            <div class="item">truck</div>
            <div class="item">van</div>
            <div class="item">bus</div>
        </div>

Instead I get the following:

Output: <div class="group">
            <div class="group"></div>
            <div class="group"></div>
            <div class="group"></div>
            <div class="group"></div>
        </div>

I have come to the conclusion that tmpl=jsTmpl in the group object is always referencing the group object's jsTemp property, not the current child in the for loop.

I have tried to use the following for the group jsRender template:

'<div class="group">{{for children}}{{include tmpl=jsTmpl}}{{/for}}</div>'

but jsRender does not like having an include inside of a for loop.

Is there any way to get the child's template and apply it in a parent's for loop?

1

There are 1 best solutions below

1
On

Nice approach.

You are missing the closing slash on {{include}}. Otherwise it should work fine.

<div class="group">{{for children}}{{include tmpl=jsTmpl}/}}{{/for}}</div>