AGURRU

AGURRU

How to merge AlpineJS x-for with HEEX templating.

Hi I don’t come from a front end background and have been trying to build some pages using HEEX templates.

I plan to create some selectable cards for a form. I had it working using the following code with simple formatting:

<%= for investment <- @investments do %>
<%= investment.investment_name %>
<% end %>

I feel link I have tried all the syntax possibilities under the sun to use the AlpineJS x-for functionality with the above HEEX templating code.

Can someone please show me how I can use the x-for functionality in place of the above?

Many Thanks,

Sam

Most Liked

msimonborg

msimonborg

<.form ...></.form> is a newer function component that plays nicer with LiveView as I understand it, so I usually default to that since I also default to LiveView :smile: No need to change what you have for a regular view.

To hopefully clear up some of your confusion:

  • Use @ for assigns that you pass into the template on the Plug.Conn, e.g. @investments
  • The caveat is assigns itself, which is available in the template without @
  • Don’t use @ for regular variables that you declare inside the template, e.g. f in form_for and investment in for investment <- @invesments do
  • You always need to interpolate Elixir code into your template. With HEEX there are now two ways to do this for different scenarios. The original EEX way <%= ... %> must be used to generate raw output e.g. <p class="foo"><%= :foo %></p>. For tag attributes use curly braces e.g. <p class={:foo}>foo</p>. This works with both HTML tags and Phoenix function components. You can also do something like <p {assigns}> if you just want to pass an entire map or keyword list to the element/component as attributes.
  • An atom is just a value, not a variable, so when you are doing <%= form_for :payment ... %> you are just declaring that this is the "payment" form for the "payment" params, sending to your controller as %{"payment" => payment_params} = params. If you have a Payment changeset in your assigns then this name will be inferred for you when you write <%= form_for @changeset ... %> and you will still end up with %{"payment" => payment_params} = params with the added benefit of validations and error reporting
msimonborg

msimonborg

Welcome @AGURRU! I think it would be helpful to know why you want to use Alpine.js to render a list of elements rather than just using the Elixir/EEX code you already have? The code you have is great and gets the job done. What you’re asking for is possible though. If @investments is a list of maps, you will have to encode the whole list to JSON first

<ul x-data={"{ investments: #{Jason.encode!(@investments)} }"}>
  <template x-for="investment in investments">
    <li x-text="investment.investment_name"></li>
  </template>
</ul>

But if @investments is a list of Ecto schema structs, which is very likely if the data is coming from your database, then that will not work because you cannot encode structs to JSON. You can convert them to maps first but you’d still have a problem because you cannot encode the :__meta__ field or any associations either, so you’d have to drop those keys from the map, e.g.

<ul x-data={"{ investments: #{Jason.encode!(Enum.map(@investments, &(Map.from_struct(&1) |> Map.drop([:__meta__, :account]))))} }"}>
  <template x-for="investment in investments">
    <li x-text="investment.investment_name"></li>
  </template>
</ul>

This could be refactored into a helper function but even then it’s quite complicated and verbose. If you only need the investment_name you could just map over that field and simplify it a little, but then you lose flexibility to access the rest of the record if you need to

<ul x-data={"{ investment_names: #{Jason.encode!(Enum.map(@investments, &(&1.investment_name)))} }"}>
  <template x-for="investment_name in investment_names">
    <li x-text="investment_name"></li>
  </template>
</ul>

Overall, this is all going against the grain of the framework, and doing simple rendering work in the client that is much more easily done on the server in a clearer and more idiomatic way. I would suggest only using Alpine.js for interactive elements that server-rendering can’t perform, like drop-downs, hide/show elements, animation etc.

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
Tee
can someone please explain to me how Enum.reduce works with maps
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
mgjohns61585
Could someone help me? I’m making my first elixir program, number guessing game. I can’t figure out how to convert the user’s guess from ...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
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
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36128 110
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement