Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra Ruby lines inside If statements cause problems in Haml?

I'm trying to put some (non-rendered) comments inside an If/Else statement in one of my Haml views, but it seems to be causing problems.

I would like to have the following code:

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

- # Stuff like _____ activates the else statement
- else
  (Some other code)

Unfortunately, Rails throws me this error:

Got "else" with no preceding "if"

If I remove the 'else' comment, i.e.

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

- else
  (Some other code)

Everything works as intended. The problem is NOT the comment itself. I have to delete the actual line of Ruby code (including the hyphen) to get it to render. That is, even if I just leave a blank line preceded by a hyphen, like this:

- # Stuff like ______ activates the if statement
- if @condition
  (Some code)

-
- else
  (Some other code)

I get the same error. Other potentially-relevant details: There is more code later that is on the same indentation level as the if/else statement (not inside it), and the whole thing is nested inside a form. Could someone explain to me what's going wrong? Thanks so much!

P.S. This is my first SO question, so if I've presented this inappropriately, please let me know.

like image 952
Sawyer Bernath Avatar asked Jun 23 '13 20:06

Sawyer Bernath


Video Answer


1 Answers

The HAML reference says:

Ruby blocks, like XHTML tags, don’t need to be explicitly closed in Haml. Rather, they’re automatically closed, based on indentation. A block begins whenever the indentation is increased after a Ruby evaluation command. It ends when the indentation decreases (as long as it’s not an else clause or something similar).

So, when you decrease the indentation, and that line isn't an else clause (or similar, elsif for example), the if finishes – an end is added implicitly. Then of course the else line is invalid

Your solution is to indent the comment, either before or after the else clause:

- if @condition
  - # Stuff like ______ activates the if statement
  (Some code)

- else
  - # Stuff like _____ activates the else statement
  (Some other code)
like image 127
Gareth Avatar answered Nov 11 '22 20:11

Gareth