Arne L.
Arne L.

Reputation: 2320

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

Upvotes: 5

Views: 2445

Answers (4)

matt
matt

Reputation: 79783

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.

Upvotes: 3

Eugene Dorian
Eugene Dorian

Reputation: 917

I think you need to escape this character. Try "\|".

Upvotes: 0

Flo
Flo

Reputation: 540

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

Upvotes: 9

Hauleth
Hauleth

Reputation: 23586

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

.menu ul li:after {
  content: '|';
}

Upvotes: 1

Related Questions