mythicalprogrammer

mythicalprogrammer

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

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

sfusato

You can also use the bracket-based access syntax like this: @company.country[:name]

Furthermore, the bracket-based access syntax transparently ignores nil values. When trying to access anything on a nil value, nil is 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

NobbZ

For me it seems top work arbitrary deep:

iex(1)> nil[:i][:can][:go][:as][:many][:levels][:i][:want]
nil
LostKobrakai

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

Last Post!

mwu

mwu

I had the same issue as @Miserlou, and settled on the solution below:

I have an App.Helpers module that I’ve aliased in app_web.ex
(though for just this, it probably makes more sense as AppWeb.Helpers):

defp html_helpers do
  quote do
    ...
    alias App.Helpers
    ...
  end
...
end

In App.Helpers:

defmodule App.Helpers do
  @moduledoc """
  Global helper functions
  """

  @doc """
  Gets a field from a struct that can be deeply nested.
  Returns nil if key is not found.

  To be used in heex templates.
  """
  @spec get_field(struct(), [atom()]) :: any()
  def get_field(struct, keys) do
    access_keys = Enum.map(keys, &Access.key(&1))
    get_in(struct, access_keys)
  end
...
end

Then, I use it in heex templates like so:

<%= Helpers.get_field(@foo, [:bar, :baz]) %>

It’s the same thing as:

<%= get_in(foo, [Access.key(:bar), Access.key(:baz)]) %>

but I got tired of repeatedly typing Access.key and its verbosity when I needed to access a field in a struct returned by Ecto where the preloaded association(s) may be nil.

Edit:
Helpers.get_field/2 can be extended with a third parameter to return some other default value like so:

@spec get_field(struct(), [atom()], any()) :: any()
def get_field(struct, keys, default \\ nil) do
  access_keys = Enum.map(keys, &Access.key(&1))

  case get_in(struct, access_keys) do
    nil -> default
    other -> other
  end
end
<%= Helpers.get_field(@foo, [:bar, :baz], "No data") %>

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews