Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

haml

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

like image 419
haml_user Avatar asked Feb 15 '11 21:02

haml_user


3 Answers

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.

like image 158
superluminary Avatar answered Sep 28 '22 16:09

superluminary


You can make the attribute conditional using this constuct:

%{:id => ('A' if request.path_info.include? 'A')}
  "Text"
like image 45
Erik Avatar answered Sep 28 '22 14:09

Erik


What about simply saving it inside a local variable?

- text = "Text"     
- if !request.path_info.include? 'A'
  %div{:id => 'A'}
    = text
- else
  = text
like image 31
Tumas Avatar answered Sep 28 '22 16:09

Tumas