Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A variable or/with a default value in a Phoenix template

What's the more elegant and shorter way to do this in Phoenix/Elixir?

<title><%= @page_title %></title>

I can, of course, define @page_title in each action of each controller, but I want it to have a default value if I haven't defined it in an action and and haven't passed it to a template.

How can I do that? This doesn't work:

<title><%= @page_title || "my title" %></title>
like image 519
Andrey Avatar asked Oct 24 '25 04:10

Andrey


1 Answers

If you access the variable through the assigns map with the bracket syntax, you won't get an error if the variable is not set; instead you'll get nil, which you can chain with || to provide a default value:

<title><%= assigns[:page_title] || "my title" %></title>
like image 112
Dogbert Avatar answered Oct 26 '25 22:10

Dogbert