1252748
1252748

Reputation: 15362

Handlebars dynamic inline partial

I have a few lines of markup that I'd like to avoid keeping in an external partial file, but it should be rendered based on a variable value, either IN_PROCESS or DONE. I can make inline partials and render them based on static names:

{{#* inline  "IN_PROCESS"}}IN_PROCESS{{/inline}}
{{#* inline  "DONE"}}DONE{{/inline}}

{{> IN_PROCESS }}
{{> DONE }}

However I cannot figure out how to combine that with the () dynamic values syntax I have read about here.

So something like,

{{> (data.status) }}
     └─────────┘ data.status would be either 'IN_PROCESS' or 'DONE'

Is this possible?

Upvotes: 0

Views: 1453

Answers (1)

Matt Davis
Matt Davis

Reputation: 1337

I believe you want something similar to this:

{{#* inline  "IN_PROCESS"}}IN_PROCESS{{/inline}}
{{#* inline  "DONE"}}DONE{{/inline}}

{{> (lookup . 'status')}}

{{> (lookup . 'status')}} will look through the JSON data object for its status attribute. That is if you're passing your data in something like this:

var template = Handlebars.compile(**your source**);
$('body').append(template(data));

JSFiddle Example

The dot represents the data object that has been passed into the template function. The template function has no way of knowing what the object's name was:

template(inputData){
    // This function wouldn't know that inputData.status was originally data.status
}
var data = {status: "DONE"};
template(data);

The dot is therefore used to tell "template" when searching for a parent that inputData should be the parent and we're looking for "status" as a child. I believe that is the use of it. I actually can't find any documentation regarding its use but all lookup's seem to be in the format lookup parent child so I assume that's the reasoning.

Upvotes: 3

Related Questions