Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional values in Elixir/Phoenix EEx shared templates

I'm trying to pass values inside Phoenix EEx shared templates (templates that I reuse). So far, so good, but now I would like to make some of them mandatory and others optional. For example:

<a href="<=% @url %>" class="core Item <%= className %>">
  • url should be mandatory - this is the default (OK);
  • className should be optional - I can't make it because if I don't include it when calling the template (<%= render MyProject.SharedView, "myTemplate.html", url:"logo2.png" %>) there's an error. How can I do this?
like image 617
Paulo Janeiro Avatar asked Nov 06 '15 08:11

Paulo Janeiro


1 Answers

Using @class_name (by convention variables should be written in snake_case) will raise if the key does not exist in assigns.

You can use assigns[:class_name] which will not raise if the key does not exist in assigns is not set.

Prior to Phoenix 0.14.0 @company would return nil if it was not set. It was changed to raise so that the assignment would be explicit (explicit over implicit.)

For this reason, you should also consider explicitly passing a nil class_name (As recommended in this comment):

<%= render MyProject.SharedView, "myTemplate.html", url:"logo2.png", class_name: nil %>
like image 67
Gazler Avatar answered Oct 03 '22 03:10

Gazler