问题
In Meteor 0.7 and earlier I had a generalized conditional #withif
block helper that combines the #if
and #with
block helpers: It renders some contents with the data context set to the object in question when it existed, and something else with the default data context if it didn't exist:
Handlebars.registerHelper "withif", (obj, options) ->
if obj then options.fn(obj) else options.inverse(this)
The usage in a template would be something like the following, where doc
has a field foo
:
{{#withif doc}}
{{> doSomethingWith foo}}
{{else}}
Document doesn't exist!
{{/withif}}
In Meteor 0.8, this seems to be much more convoluted to do. Basically, I'd like this block helper to choose between UI.contentblock
and UI.elseblock
and set the data context appropriately based on whether the referenced object exists in the context or not. What's the cleanest way to do this?
I'm aware that I could just deconstruct this as
{{#if this}}
{{> UI.contentBlock this}}
{{else}}
{{> UI.elseBlock}}
{{/if}}
However, I avoided this in Meteor 0.7 and earlier due to the unnecessary performance penalty versus the helper above. If it's possible to show that this doesn't get any slower in Blaze, I'd be happy to stick with it (I know Blaze generates code for rendering).
来源:https://stackoverflow.com/questions/22792076/cleanest-way-to-implement-a-conditional-with-helper-template-in-meteor-0-8-0-bl