Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically render partial templates using mustache

Is there a way to dynamically inject partial templates (and have it work the same way in both Ruby & Javascript)? Basically, I'm trying to render different types of objects in a list.

The best I can come up with is this:

<div class="items">
{{#items}}
<div class="item">
  {{#is_message}}
  {{> message}}
  {{/is_message}}

  {{#is_picture}}
  {{> picture}}
  {{/is_picture}}
</div>
{{/items}}
</div>

I'm not super-psyched about this approach. Is there a better way?

Also note that the different types of models for the views can have non-similar fields. I suppose I could always go to the lowest common denominator and have the data hash contain the html, however I would rather use the mustache templates.

like image 597
Brian Takita Avatar asked May 28 '10 21:05

Brian Takita


1 Answers

I did the same thing you did, and for each property type i needed a dynamic partial, I just set a dynamic variable in the js data model that's being rendered in the template...

eval("this.set({is_" + this.get("propertyType") + ": true})")

or

this["is_" + propertyType] = true

At least I don't have to manually set the 'is_whatever' variable...

It would be cool if mustache.js or ICanHaz.js had some clever syntax for dynamic properties inside of mustache tags... maybe something like this:

{{>{{message}} }}
like image 82
Dan Tocchini Avatar answered Sep 25 '22 13:09

Dan Tocchini