Conditional HAML expression possible with ternary operator

Trying to come up with a more compact way to express this conditional expression in HAML and Ruby, possibly with a ternary operator:

- if @page.nil? %br (nothing yet) - else %br #{@page.name} 

(search for a similar approach by a simplified way to conditionally check whether to add a class to a HAML template )

Your help will be appreciated :)

+6
source share
4 answers

The code you have makes the text a child of the <br> element; which is undesirable. I think you really meant:

 %br - if @page.nil? (nothing yet) - else #{@page.name} 

To do this, you can simply:

 %br #{@page.nil? ? "(nothing yet)" : @page.name} 

or

 %br = @page.nil? ? "(nothing yet)" : @page.name 

Or simply:

 <br>#{@page ? @page.name : "(nothing yet)"} 

However, personally, I would "fix" this in the controller so that you always have an @page , with something like:

 unless @page @page = Page.new( name:"(nothing yet)", … ) end 

With this, you can fill out the one that looks like a new / blank / insignificant page and let your view treat it like any other. Your @page will still not have @page.id , so you can use this for tests to decide whether you are creating a new element or editing an existing one.

Here's how I handle all my forms that can be used to create or edit an element: provide default values ​​by creating (but not adding to the database) an element with default values.

Also: you create <br> , which will almost never be a good idea , and you create it with Haml, which should not be used to mark up content . You can step back and think about what you are doing.

+14
source

Just do:

 %br = @page.try(:name) 
+1
source

You can also insert a line assuming - order_count = 12 : %h5= Ordered #{ order_count == 1 ? "1 item" : "#{order_count} items" } for this session %h5= Ordered #{ order_count == 1 ? "1 item" : "#{order_count} items" } for this session

0
source
 %br = @page ? (nothing yet) : #{@page.name} 
-1
source

Source: https://habr.com/ru/post/924903/


All Articles