EEx - multiple anonymous function as arguments

I want to write:

<%= my_function f, fn arg -> %>
  some html
<%= end, fn arg -> %>
  another html
<% end %>

But I got a compilation error in third line: unexpected token: end

This code doesn’t produce error:

<%= my_function f, fn arg -> nil end, fn arg -> %>
  another html
<% end %>

Am I doing something wrong?

1 Like

I think the second <%= should be a <%, but I haven’t tried it out.

3 Likes

Still doesn’t work. I think that EEx just doesn’t like when there is something after anonymous function with html. This also doesn’t work:

<%= my_function f, fn arg -> %>
  some html
<%= end, 2137 %>
1 Like

It is not just anonymous functions, eex does not like non-blocks (like do/end) being broken up between different eex statements, it expects everything to be in a single statement as far as my testing has shown me.

At those times I just break up the template into smaller templates and just pass in the anonymous function calls to them, plus it makes the templates smaller and ‘usually’ more readable. :slight_smile:

I’ve not tried this, just thought of it, but you could try:

<%= my_function f, fn arg -> ~e"""
   some html
""" end, fn arg -> ~e"""
  another html
""" end %>

So just embed eex templates in the eex templates (which will not have a run-time overhead at all, eex templates, no matter how deep, inline into an iolist). ^.^

3 Likes

missing terminator: end (for "fn" starting at line 3)
:smiley:

So this is the only solution for now

<% template1 = fn arg -> ... end %>
<% template2 = fn arg -> ... end %>
<%= my_function f, template1, template2 %>
1 Like

Er, I forgot an end in my example above, can try again. ^.^

1 Like

Now it works. Anyway, putting this functions in variables is more readable

2 Likes

I think it works, you just didn’t remove the = from the last end again.