Haml::SyntaxError at / Illegal nesting: content can't be both given on the same line as %li and nested within it

StackOverflow https://stackoverflow.com/questions/21742270

  •  10-10-2022
  •  | 
  •  

Question

I'm using sinatra and following this tutorial here and I have tried rewrite this code with HAML:

<form action="/task/create" method="POST">
<input type="text" name="name" id="name">
<input type="submit" value="Add Task!"/>
</form>

<h2>Tasks:</h2>
<% unless @tasks.empty? %>
<ul>
<% @tasks.each do |task| %>

<li <%= "class=\"completed\"" if task.completed_at %>>
<a href="/task/<%=task.id%>"><%= task.name %></a>
</li>
<% end %>
</ul>
<% else %>
<p>No Tasks!</p>
<% end %>

Here is my HAML code:

%form{action: "/task/create", method: "POST"}
%input{type: "text", name: "name", id: "name"}
%input{type: "submit", value: "Add Task!"}
%h2 Tasks:
- unless @tasks.empty?
%ul
  - @tasks.each do |task|
    %li= "class=\"completed\"" if task.completed_at 
      %a{href: "/task/#{task.id}"}= task.name
- else
%p No Tasks!

And I get the following error when I try to look at the page:

Haml::SyntaxError at / Illegal nesting: content can't be both given on the same line as %li and nested within it.

Any helps on this would be great.

Ivo

Was it helpful?

Solution

You have a couple of issues going on. First your if task.completed_at needs to be lifted up so that it encompasses both the li and anchor tags; as you had it it will only apply to the li.

Second issue is you aren't declaring your class correctly. In HAML, the elements class should be declared preferably in dot notation like such.

%li.your_class_name_here

Alternately you can declare your classes like this.

%li{:class => "class_name_here"}

Either of these method creates an empty element that does not contain content, and as such a content element can then be nested within it like you are attempting with your anchor tag.

As soon as you use that equal sign you are declaring content for the element and HAML will not handle nesting content on the same element; which is essentially what you have told it to do with this line

%li= "class=\"completed\""

Essentially this is saying to HAML, create an li element and assign class="completed" as content of this element...

Below I have provided a working example of what you are trying to accomplish.

%form{action: "/task/create", method: "POST"}
%input{type: "text", name: "name", id: "name"}
%input{type: "submit", value: "Add Task!"}
%h2 Tasks:
- unless @tasks.empty?
  %ul
    - @tasks.each do |task|
      - if task.completed_at
        %li.completed
          %a{href: "/task/#{task.id}"}= task.name
- else
  %p No Tasks!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top