Cleanest way to implement a conditional with helper/template in Meteor 0.8.0 (Blaze)

南楼画角 提交于 2019-12-25 02:35:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!