Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to let a line end with | (pipe) in HAML?

The problem is that a | at the end of a line (seperated by whitespace) is recognized as syntax for advanced line-breaks. What to do if you want to get this character as output?

Example

Say you want to create a menu like

Section 1 | Section 2 | ...

Note: if this is just what you want then take a look at concatenate link_to with pipe.

Wether or not a link is shown depends on a certain condition. In HAML/Ruby on Rails this could look like which does not work

%div.menu
    -if condition1?
        #{link_to 'Section 1', section_1_path} |
    -if condition2?
        #{link_to 'Section 2', section_2_path} |
    -if condition3?
        ...

Work-around

As a (somehow dirty) work-around I changed the code:

%div.menu
    -if condition1?
        #{link_to 'Section 1', section_1_path} #{'|'}
    -if condition2?
        #{link_to 'Section 2', section_2_path} #{'|'}
    -if condition3?
        ...
like image 237
Arne L. Avatar asked Sep 12 '12 12:09

Arne L.


3 Answers

No need for escaping, just the same indentation than the element u want separated.

%div.menu
  -if condition1?
    #{link_to 'Section 1', section_1_path} 
    |
  -if condition2?
    #{link_to 'Section 2', section_2_path} 
    |
  -if condition3?
      ...

you can try this in browser: online haml editor: rendera or html2haml

like image 133
Flo Avatar answered Oct 18 '22 01:10

Flo


The Haml parser look fo the | character preceded by whitespace to signify a multiline block. You could use this to create a workaround by using a HTML character reference instead of a normal space in your Haml:

%div.menu
  -if condition1?
    #{link_to 'Section 1', section_1_path} |
  -if condition2?
    #{link_to 'Section 2', section_2_path} |
  -if condition3?
    ...

This way Haml won’t see the space so will treat the pipe as a literal, but the space will appear in the browser.

Whether you prefer this workaround to your own is likely a matter of taste. In this particular case I think a css based solution would be better, but that would depend on what browsers you need to support.

like image 36
matt Avatar answered Oct 18 '22 02:10

matt


Menu should be a list so make it an unordered list and in CSS:

.menu ul li:after {
  content: '|';
}
like image 30
Hauleth Avatar answered Oct 18 '22 02:10

Hauleth