Damien Compère
Damien Compère

Reputation: 269

Haml, ruby on rails error: Encountered a syntax error while rendering template

I tried to execute the following code but I got:

"Encountered a syntax error while rendering template:"

Here is my view:

%section
    %article
        - if @toss % 2 === 0
            %p the player #{@player_one.name} start the fight !
        - else 
            %p the player #{@player_two.name} start the fight !

        - while @hp_player_one > 0 && @hp_player_two > 0 
            - @hp_player_one -=  @player_two.attack
                %p  There is only #{@hp_player_one.to_s} point to #{@player_one.name}
            - @hp_player_two -=  @player_one.attack
                %p  There is only #{@hp_player_two.to_s} point to #{@player_two.name}
                -if @hp_player_one <= 0 && @hp_player_two > 0
                    %p #{@player_one.name} lost 
                -elsif @hp_player_two <= 0 && @hp_player_one > 0
                    %p #{@player_two.name} lost 
                -else 
                    %p draw ! 

How do I fix it?

Upvotes: 1

Views: 1885

Answers (1)

matt
matt

Reputation: 79723

Your indentation is wrong, I think you want something like this:

%section
    %article
        - if @toss % 2 === 0
            %p the player #{@player_one.name} start the fight !
        - else 
            %p the player #{@player_two.name} start the fight !

        - while @hp_player_one > 0 && @hp_player_two > 0 
            - @hp_player_one -=  @player_two.attack
            %p  There is only #{@hp_player_one.to_s} point to #{@player_one.name}
            - @hp_player_two -=  @player_one.attack
            %p  There is only #{@hp_player_two.to_s} point to #{@player_two.name}
            -if @hp_player_one <= 0 && @hp_player_two > 0
                %p #{@player_one.name} lost 
            -elsif @hp_player_two <= 0 && @hp_player_one > 0
                %p #{@player_two.name} lost 
            -else 
                %p draw ! 

In particular you shouldn’t indent after a line like

- @hp_player_one -=  @player_two.attack

as this doesn’t start a block. Haml sees the indentation after this line and assumes that it is the start of a block, and so inserts a corresponding end into the generated Ruby. These extra ends will give you unexpected end, expecting end-of-input syntax errors.

Upvotes: 2

Related Questions