开发者_如何学JAVA- if !request.path_info.include? 'A'
%{:id => 'A'}
"Text"
- else
"Text"
"Text" is written twice. How can I do to write it just once and in the same time check if the path_info includes 'A'?
There are two ways to do this. Using a partial, or using a content_for block:
If "Text" was longer, or was a significant subtree, you could extract it into a partial. This would DRY up your code a little. In the example given this would seem like overkill.
The better way in this case would be to use a content_for block, like so:
- if !request.path_info.include? 'A'
%{:id => 'A'}
=yield :content
- else
=yield :content
-content_for :content do
Text
Here we yield to the content_for block in both places, removing the need to duplicate "Text". I would say in this case this is your best solution.
You can make the attribute conditional using this constuct:
%{:id => ('A' if request.path_info.include? 'A')}
"Text"
What about simply saving it inside a local variable?
- text = "Text"
- if !request.path_info.include? 'A'
%div{:id => 'A'}
= text
- else
= text
It's not ideal, but you can use HTML with HAML. The way I've done this is:
- if !request.path_info.include? 'A'
<div id="A">
Text
- if !request.path_info.include? 'A'
</div>
This is messy with such little text, but when Text
is a large code block that you want to optionally wrap with a div
, it can really help you follow DRY.
The short answer is you can't. HAML is a indentation specific format, hence it can't allow you to be able to do what you want without repetition since the two conditions are separate paths while parsing.
精彩评论