Paulo Janeiro
Paulo Janeiro

Reputation: 3211

Best way to pass default parameter in templates

Sometimes inside my templates I want to define default values for some CSS properties when those values are not passed as parameters in the render function, like this:

height: <%= if @height do %><%=@height%><% else %>"50px";<%end%>

I'm wondering if there's a better (less verbose) way of doing this.

Upvotes: 2

Views: 578

Answers (1)

Dogbert
Dogbert

Reputation: 222148

You can use the fact that

  1. @ variables can also be accessed through a map named assigns,
  2. accessing a non-existent key in a map using the bracket syntax returns nil instead of raising an exception,
  3. || returns the right hand side value if the left one is nil,

and write:

<%= assigns[:height] || "50px" %>

to get the same behavior as your if/else.

Edit: if you're always setting @height, even if the value is nil, you can do this with even lesser code:

<%= @height || "50px" %>

The previous code will work even if @height is not set to any value but this will raise an exception if @height is not set.

Upvotes: 6

Related Questions