问题
I am looking to render a handlebars partial via the Lookup helper. This isn't a problem, I can do that with this code:
{{> (lookup . 'type') }}
However, if the variable type doesn't render a value that is in my partials directory, then a 500 error throws. Handlebars supports this with failover content. Such as:
{{#> myPartial }}
Failover content
{{/myPartial}}
My question is, can I combine the lookup with the failover?
I was hoping to do something like:
{{#> (lookup . 'type') }}
Failover content
{{/(lookup . 'type')}}
回答1:
Thank you @76484 but I think I found what I was looking for:
{{#> (lookup . 'type') }}<!-- Return Nothing if Undefined -->{{/undefined}}
This avoids the need for a helper, and does exactly what I was looking for!
回答2:
I don't think there is a way to combine the dynamic lookup helper with the partial block. However, I think we can come up with a custom helper that will do the job for us.
All that our helper needs to do is to take a partial name and try to find a partial by that name in the Handlbars.partials map. If it finds a partial, it will return the result of calling that partial template with the current data context. Otherwise, our helper will return the template within its block (the failover content).
Handlebars.registerHelper('partialResolver', function (partialName, options) {
var partial = Handlebars.partials[partialName];
if (partial && !Handlebars.Utils.isFunction(partial)) {
Handlebars.partials[partialName] = partial = Handlebars.compile(partial);
}
return (partial ? partial : options.fn)(this);
});
Note: The condition in the middle is required because partials can be registered either as strings (which get compiled on demand) or as pre-compiled templates. If the partial is a string, we compile it and assign it to Handlebars.partials[partialName].
I have created an example fiddle for reference.
来源:https://stackoverflow.com/questions/45824896/handlebars-failover-content-with-lookup-helper