mythicalprogrammer
Phoenix Template: design pattern to check if exist or not
Hi guys.
I’m getting this error because of how I coded my template:
function nil.name/0 is undefined
The offending code:
<%= @company.country.name %>
What’s elixir idiomatic way of writing this to check if exist display the country name else don’t display and don’t access country.name so I don’t trigger the error? I did an if else before but I feel like there may be something better out there.
Thanks
Marked As Solved
aptinio
You can add a country_name/1 function in your View module like so:
def country_name(%{country: %{name: name}}), do: name
def country_name(_), do: "" # or "No country"
Then just:
<%= country_name(company) %>
Also Liked
sfusato
You can also use the bracket-based access syntax like this: @company.country[:name]
Furthermore, the bracket-based access syntax transparently ignores
nilvalues. When trying to access anything on anilvalue,nilis returned:
This would work just fine, but perhaps won’t transmit intent as good as an if/else or a separate view function would.
NobbZ
For me it seems top work arbitrary deep:
iex(1)> nil[:i][:can][:go][:as][:many][:levels][:i][:want]
nil
LostKobrakai
I also like using the view module for doing that kind of stuff, which allows my templates to need less amount of logic. They just display what’s given.
def render("myview.html", assigns) do
country_name = assigns.company[:country][:name] || "Unavailable"
render_template("myview.html", Map.merge(assigns, %{country_name: country_name}
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








