fireproofsocks

fireproofsocks

Complex loop in EEx

I’m trying to build a loop in an EEx template that may have to iterate over a list OR a map (i.e. loop over its keys/values) and include an index (yes, I know that’s a lot).

So far, my EEx template looks like this:

The start...
<%= Enum.with_index(list)
|> Enum.map(fn {x, index} ->
    case x do
      {k, v} -> %>
        <%= k %> <%= v %>: @index: <%= index %>
    <% x -> %>
          <%= x %>: @index: <%= index %>
    <% end %>
<% end) %>
...The end.

But that results in an error:

** (TokenMissingError) nofile:12: missing terminator: end (for "fn" starting at line 3)
    lib/eex/compiler.ex:101: EEx.Compiler.generate_buffer/4
    lib/eex/compiler.ex:54: EEx.Compiler.generate_buffer/4
    lib/eex.ex:199: EEx.eval_string/3
    my_file.exs:37: (file)

A simpler EEx template works:

The start...
<%= Enum.with_index(list)
|> Enum.map(fn {x, index} -> %>
      <%= x %>: @index: <%= index %>
<% end) %>
...The end.

but that one only handles lists. I think I’m getting stuck on where exactly I’m allowed to break in and out of Elixir code within an EEx template. The basic logic works when it’s not in EEx.

Thanks for any pointers!

Most Liked

patrickdm

patrickdm

Hello, I’d try to simplify it by moving the function to the view module, using string interpolation, i.e. (disclaimer: untested code ahead…)

def eval_item(x, index) do
  case x do
    {k, v} -> 
      "#{k} #{v} : @index: #{index}"
    val ->
      "#{val} : @index: #{index}"
    end
end

or with two functions using pattern matching on arguments (that I prefer as I find it easier to read):

def eval_item({k, v} = x, index), do: "#{k} #{v} : @index: #{index}"

def eval_item(x, index), do: "#{x} : @index: #{index}"

then in the template you could just:

<%= Enum.with_index(list) |> Enum.map(&eval_item/2) %> 

hth.

kokolegorille

kokolegorille

I would even go further and put all logic in a helper function. Putting logic in the template is not something I would advise.

Somehing like

<%= do_something(list) %> 
patrickdm

patrickdm

yes, good advice! :slight_smile:

[…edit…] Putting all together would look like:

in template.html.eex

<%= iterate_over(list) %> 

in template_view.ex

def iterate_over(list) do
 list
 |> Enum.with_index()
 |> Enum.map(&eval_item/2)
end

defp eval_item({k, v} = _x, index), do: "#{k} #{v} : @index: #{index}"

defp eval_item(x, index), do: "#{x} : @index: #{index}"
Ninigi

Ninigi

<% %> doesn’t work like that (been there tried that :slight_smile:), and you can simplify the map/case by pattern matching in the function signatures.

untested:

<%= Enum.with_index(list) |> Enum.map(fn
  {{k, v}, index} ->
    "#{k} #{v}: @index: #{index}"
  {x, index} ->
    "#{x}: @index: #{index}"
end) %>

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New

We're in Beta

About us Mission Statement