0

I'd like to have my jsRender templates optionally include an "options" property to provide optional fall-backs if a property is not included; specifically rendering one element if the "options" property is included, or another if it is not. Everything works fine if the model passed in contains the property in question, but even {{if typeof ~options.someOption !== 'undefined'}} gives me Error: Cannot read property 'someOption' of undefined.

Has anyone dealt with this? If so, how do you handle properties of the model passed in that do no exist?

EDIT: This question is really about how to handle missing properties of a model. Given a model with properties A and B, if property B is missing from the model but it is referenced in the template, how can I prevent error messages and handle it's absence elegantly?

4

1 回答 1

0

您可以利用在 Javascript 中不存在的事物评估为“未定义”的事实,这相当于条件语句中的 false,并在您尝试访问的包含对象和属性周围包裹一个“if”。所以,用你的例子,你会喜欢

{{if options}}{{if options.someOption}}{{:options.someOption}}{{/if}}{{/if}}

如果 options 和 someOption 都存在,则模板将使用 options.SomeOption 呈现。否则它什么也做不了。

于 2013-03-28T17:07:01.563 回答