HAML: Create container/wrapper element only if con

2019-02-08 23:39发布

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

In other words, it always shows the content inside, but it only wraps a container around it if (some-condition) is true.

4条回答
在下西门庆
2楼-- · 2019-02-09 00:23

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>

Assuming you're doing more than just = name, you could use a partial:

- if show_paras
  %p= render "my_partial"
- else
  = render "my_partial"

You could also use HAML's surround (though this is a little messy):

- surround(show_paras ? "<p>" : "", show_paras ? "</p>" : "") do
  = name

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
查看更多
别忘想泡老子
3楼-- · 2019-02-09 00:28

The cleanest way I can think of doing is like this:

= show_paras ? content_tag(:p, name) : name

But it's not exactly haml.

Generally markup is the for the content, so if show_paras is a more presentational tweak you should probably be using css to change the behaviour of the %p instead

查看更多
可以哭但决不认输i
5楼-- · 2019-02-09 00:35

Another option is to wrap it in an alternative tag if the condition isn't met, using haml_tag:

- haml_tag(show_paras ? :p : :div) do
  = name
查看更多
登录 后发表回答