Use of phx-value-ref

I’d like to do something like this in Phoenix 1.6:

~H"""
<%= for {stock_name, value} <- @stocks do %>
  <tr>
    <td><%= stock_name %></td>
    <td><%= value %></td>
    <td><button phx-click="buy" phx-value-ref="#{stock_name}">Buy</button></td>
  </tr>
<% end %>
"""

But I do not know how to get phx-value-ref="#{stock_name}" working.

I get

%Phoenix.Socket.Message{event: "event", join_ref: "4", payload: 
%{"event" => "buy", "type" => "click", 
"value" => %{"ref" => "\#{stock_name}", "value" => ""}}, 
ref: "5", topic: "lv:phx-FqiYj4B3tZjwTAOE"}

I tried all sort of variants but I can’t get the stock_name set as a phx-value-ref. What is the correct syntax or do I have to use something totally different here?

I think I would do the following: phx-value-ref="<%= stock_name %>"

I tried <button phx-click="buy" phx-value-ref="<%= stock_name %>">Buy</button> but that creates this error:

== Compilation error in file lib/demo_web/live/clock_live.ex ==
** (Phoenix.LiveView.HTMLTokenizer.ParseError) lib/demo_web/live/clock_live.ex:34:54: expected closing `"` for attribute value

Make sure the attribute is properly closed. This may also happen if
there is an EEx interpolation inside a tag, which is not supported.
Instead of

    <div <%= @some_attributes %>>
    </div>

do

    <div {@some_attributes}>
    </div>

Where @some_attributes must be a keyword list or a map.
``

Perhaps the value of the attribute is not supported? What’s the output of stock_name is it just a string?

Dynamic html attributes in heex are denoted like this: phx-value-ref={stock_name}

11 Likes

Ah, right yes, I see where I was getting it wrong. Sorry for the misleading information!

Thanks!

doing it like this gives me the string ‘stock_name’ instead of the value of the variable

@bernardo If you’re referring to an assign you need the @ in front. You see the OP was using a value from a for comprehension, so no @.

yep, that is my case too. I have:

<%= for c <- @entries do %>
    <div>
      <a href="#" phx-click="list_folder" phx-value-remote_ids="{c.name}"><%= c.name %></a>

and "{c.name}" does not interpolates correctly (<%= c.name %> does interpolates correctly)

ok solved, the quotes were not necessary, thanks

1 Like

not just not necessary, they were taking the literals of the stuff within