Scope of variables in Eex

Hello, I have the following code on my eex or html template:

Within the <head>

<%= case @user.data["country_code"] do %>
  <% "US" -> %>
    <% currency = "USD" %>
  <% "GB" -> %>
    <% currency = "GBP" %>
  <% _ -> %>
   <% currency = "EUR" %>
<% end %>

In the <body>

<p>Current price is 100<%= currency %></p>

the above gives an “undefined function currency/0” , so I’m not sure if I’m doing it wrong and there’s a proper way to do this, or this actually won’t work due to scope, as I tested the variable outside of the case statement and it works.

This works:

<% currency = "USD" %>
<p>Current price is 100<%= currency %></p>

TIA

This isn’t just eex, this is how scoping works in Elixir.

Try:

<%= currency = case @user.data["country_code"] do %>
  <% "US" -> %>
    <% "USD" %>
  <% "GB" -> %>
    <% "GBP" %>
  <% _ -> %>
   <% "EUR" %>
<% end %>

This would be better pulled into a helper function, though. Maybe like:

def currency("US"), do: "USD"
def currency("GB"), do: "GBP"
def currency(_), do: "EUR"
5 Likes

Tried the code with some modifications and it did work, below is what I ended up using:

<% currency = case @user.data["country_code"] do %>
  <% "US" -> %>USD
  <% "GB" -> %>GBP
  <% _ -> %>EUR
<% end %>

A helper would probably be best, but in this instance there’s a chance that it will need to be updated every now and then, which meant I would have to PR every change, so was hoping this could be on the front-end only.

Thanks mate.

Is that a working agreement at your office? Are you using classic Phoenix views or LiveView? If it’s the former, your helper function can go in the view which should really still be considered “frontend”, otherwise it can just be a private function right in your LiveView. Of course, I don’t know the politics of your office.

We have a dashboard UI with an editor that we use to code the pages. We use classic views but not sure if private functions will work in it though, might need to read up on it.