[Haml] Solution for "syntax error, unexpected keyword_ensure, expecting keyword_end" Error
I encountered the following error while using Haml in Ruby on Rails.
■ Error Message
syntax error, unexpected keyword_ensure, expecting keyword_end
The cause was that I wrote the code inside if statement branches without proper indentation, as shown below.
I wanted to align %ul.nav with the same indentation, so I wrote it like this, but this was wrong.
%div.container.nav-collapse
%ul.nav
%li #{ link_to "Article", "/articles" }
- if user_signed_in?
%ul.nav
%li #{ link_to "Signed in as #{ current_user.email }", "#" }
%ul.nav
%li #{ link_to "Sign out", destroy_user_session_path, :method => :delete }
- else
%ul.nav
%li #{ link_to "Sign up", new_user_registration_path }
%ul.nav
%li #{ link_to "Sign in", new_user_session_path }
The correct way is to write it as follows:
%div.container.nav-collapse
%ul.nav
%li #{ link_to "Article", "/articles" }
- if user_signed_in?
%ul.nav
%li #{ link_to "Signed in as #{ current_user.email }", "#" }
%ul.nav
%li #{ link_to "Sign out", destroy_user_session_path, :method => :delete }
- else
%ul.nav
%li #{ link_to "Sign up", new_user_registration_path }
%ul.nav
%li #{ link_to "Sign in", new_user_session_path }
From the middle, the indentation of %ul.nav drops one level and looks awkward, but in the output HTML, they are beautifully aligned at the same indentation level, so I was relieved.
That’s all from the Gemba.