5
votes

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?
1

1 Answers

15
votes

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 %>