atomAltera
atomAltera

Reputation: 1781

How to stop rendering page/partial

I interested about can I interupt template rendering in the middle of template. For example:

items/index.html.haml

%h2 Items

-if @items.empty?
  %h3 There are no items
  /X statement/ 


[email protected] do |item|
  /items rendering/ 

So if there are no items, message will be displayed and page rendering will be interrupted, otherwise item list will be rendered. Only way I can do it now, is throw if-else statement. I tried to use return in place of X statement, but seems like it not works like I expect

Upvotes: 2

Views: 1269

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51151

Basically, you can't do this. What you can do is check if @items are empty BEFORE you start rendering items index:

- if @items.empty?
  %h3 There are no items
- else
  %h2 Items
  - @items.each do |item|
    /items rendering/

Upvotes: 3

Simone Carletti
Simone Carletti

Reputation: 176402

The way to achieve that result is exactly by using the if-else statement.

I'm not familiar with Haml, but the logic using the good "old" ERB is

<% if @items.empty? %>
  There are no items
<% else %>
  <% @items.each do |item| %>
  ...
  <% end %>    
<% end %>    

You can use a double if, if you prefer to split the conditions

<% if @items.empty? %>
  There are no items
<% end %>    

<% @items.each do |item| %>
...
<% end unless @items.empty? %>    

Upvotes: 5

Related Questions