简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM