How can I do to write “Text” just once and in the same time check if the path_info includes 'A'?

╄→гoц情女王★ 提交于 2019-12-23 11:53:07

问题


- 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'?


回答1:


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.




回答2:


You can make the attribute conditional using this constuct:

%{:id => ('A' if request.path_info.include? 'A')}
  "Text"



回答3:


What about simply saving it inside a local variable?

- text = "Text"     
- if !request.path_info.include? 'A'
  %div{:id => 'A'}
    = text
- else
  = text



回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/5009443/how-can-i-do-to-write-text-just-once-and-in-the-same-time-check-if-the-path-in

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!