HAML:仅在条件为true时创建容器/包装器元素 [英] HAML: Create container/wrapper element only if condition is true
问题描述
远射,但我想知道是否有任何办法可以做这样的事情:
Longshot, but I'm wondering if there's any way to do something like this:
%p # ONLY SHOW THIS IF LOCAL VARIABLE show_paras IS TRUE
= name
换句话说,它总是在其中显示内容,但是只有在(某些条件)为true时,它才会在其周围包装一个容器.
In other words, it always shows the content inside, but it only wraps a container around it if (some-condition) is true.
推荐答案
您可以使用原始html,但随后必须在开头和结尾处都使用if语句:
You could use raw html, but then you'd have to have the if statement both at the beginning and end:
- if show_paras
<p>
= name
- if show_paras
</p>
假设您要做的不只是= name
,还可以使用部分:
Assuming you're doing more than just = name
, you could use a partial:
- if show_paras
%p= render "my_partial"
- else
= render "my_partial"
您还可以使用HAML的surround
(尽管有点杂乱):
You could also use HAML's surround
(though this is a little messy):
- surround(show_paras ? "<p>" : "", show_paras ? "</p>" : "") do
= name
最后,我可能根本不会尝试忽略p
标记,而只是使用CSS类来设置两种不同的p
样式以符合我想要的方式:
Finally, what I would probably do is not try to omit the p
tag at all, and just use CSS classes to set up two different p
styles to look the way I want:
%p{:class => show_paras ? "with_paras" : "without_paras"}
= name
这篇关于HAML:仅在条件为true时创建容器/包装器元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!