如何在 HAML 中使用局部变量的默认值?
我有一个 HAML 模板,我想要渲染它并可选择提供一个局部变量(此处称为 post),以便它可以使用提供的变量作为元素属性的值,或者回退到显式默认值。
下面的代码显示了我的意思,但如果未提供 post
,它将无法运行。有一个干净的解决方案吗?我有很多这样的字段,我不想继续用 - if Defined?
语句重复它们,这是我能想到的唯一的其他选择。
%label
Post title
%input{:name => "title",
:value => (defined? post) ? post.title : ""} }
I have a HAML template that I want to render and optionally provide a local variable to, here called post, so that it either uses the provided variable as the value of an element attribute, or falls back to an explicit default.
The code below shows what I mean, but it fails to run if post
isn't provided. Is there a clean solution to this? I have quite a few of these fields, and I'd rather not have to keep duplicating them with - if defined?
statements, which is the only other alternative I can think of.
%label
Post title
%input{:name => "title",
:value => (defined? post) ? post.title : ""} }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试这样做:
您不需要检查定义,因为
nil
在 Ruby 解释器中被视为 false。 Russ Olsen 的《Eloquent Ruby》 的这段摘录对其进行了最好的描述:如果这是一个 Rails 应用程序,更雄辩的解决方案是使用 Rails
try
方法:try
方法调用由在类中传递的符号标识的方法除非类本身是nil
,在这种情况下它将返回nil
(haml会自动转换为空白字符串)。 在此处了解有关 Rails try 方法的更多信息。Try this doing this:
You don't need to check with defined because
nil
is treated as false in the Ruby interpreter. This excerpt from Eloquent Ruby by Russ Olsen describes it best:If this is a Rails app, a more eloquent solution would be to use the Rails
try
method:The
try
method invokes the method identified by the symbol that's passed in on the class unless the class itself isnil
, in which case it will returnnil
(which haml will automatically convert to a blank string). Read more about the rails try method here.如果你只是想处理某些变量为零的情况,你可以使用
try
方法。例如:当post为nil时,只返回nil;否则返回 post.title。
但是,如果您想提供显式默认值,那么您应该编写一个帮助程序(类似于
default_if_nil
),或者对try
进行猴子修补方法使其能够指定默认值。If you just want to deal with the case that some variable be nil, you can use the
try
method. For example:When post is nil, it just returns nil; otherwise post.title is returned.
However, if you want to provide explicit default values, then you should either write a helper (something like
default_if_nil
) or monkey-patch thetry
method to make it able to specify default values.啊,原来真正的问题是在 Sinatra 中,它定义了一个
post
方法来定义 HTTP posts 的处理程序,并且 HAML 渲染器可以看到这一点。如果您向渲染器提供了一个
post
变量,它会隐藏它,因此模板可以正常工作,但否则post
实际上是一个函数,因此已定义? 是 true,但显然没有
title
属性。只需更改变量的名称即可使一切按我的预期工作。
Ah, turns out the real problem was that this is in Sinatra, which defines a
post
method to define handlers for HTTP posts, and the HAML renderer can see this.If you provided a
post
variable to the renderer it hides it, so the template works fine, but otherwisepost
is actually a function, and sodefined?
is true, but clearly there's notitle
property.Just changing the name of the variable makes everything work as I expected.