引用可能未在部分中定义的变量的严格方法是什么?
我的局部变量中有一些局部变量,它们可能会也可能不会由渲染它们的模板传递,例如:on_question_page
。如果我在该页面上,我会将其视为 true,但在其他地方我会跳过它。
问题是我无法直接引用该变量,因为在未定义它的地方它会引发错误。
这意味着我最终会在部分代码的顶部得到很多这样的代码:
on_question_page = defined?(on_question_page) ? on_question_page : false
凌乱。有没有更干净的方法来访问这些可选变量?
I have a few local variables in my partials which may or may not be passed by the template that renders them, for instance: on_question_page
. If I'm on the page I pass it as true but elsewhere I skip it.
The problem is that I can't reference that variable directly because in the places it isn't defined it throws an error.
This means that I end up with a lot of code like this at the top of my partials:
on_question_page = defined?(on_question_page) ? on_question_page : false
Messy. Is there a cleaner way to access these optional variables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
on_question_page
未定义、false
或nil,您可以使用
,即使用布尔运算符测试时计算结果为on_question_page ||= false
分配false
false
的内容。You can use
on_question_page ||= false
to assignfalse
ifon_question_page
is undefined orfalse
ornil
, that is, something which evaluates tofalse
when tested with boolean operators.您可以使用
||=
运算符you might use
||=
operator如何在始终包含的位置定义默认值并在您的部分中覆盖它?
这样您就不需要检查它是否可用,甚至可以根据需要轻松更改默认值。
How about defining the default value at a position which is always included and overriding it in your partial?
That way you do not need to check whether it is available and you could even change the default value easily if required.
我认为解决方案是使用绑定和助手:
绑定允许我们将视图的评估上下文传递给助手,并在那里完成所有杂乱的工作。这会将逻辑移出视图并移入助手。
I think the solution would be to use bindings and a helper:
Bindings allow us to pass the evaluation context of the view in to a helper and do all the messy work in there. This moves the logic out of the view and in to a helper.