Concat string wit attributes in html attributes

I’ve been starting to work with Phoenix framework, I am currently following some LiveView tutorials. The tutorial that I am currently following has some syntax that is deprecated: Specifically when concatenating a string with an attribute in the attributes of an Html tag:

Old way:

def render(assigns) do
    ~H"""
    <div id="post-<%= @post.id %>" class="post"></div>
    """
end

But with the above shows me the following compilation error:

.../post_component.ex:6:19: 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>

How can I get the tag id as follows: "post-1"?

You can use the new syntax with Heex (~H):

<div id={"post-#{@post.id}"} class="post"></div>

This post about Phoenix 1.6 upgrade should help you for the changes that have come up since it came out (note that LiveView 0.17 added/changed a number of other things, so look at the changelog for them too):
https://www.phoenixframework.org/blog/phoenix-1.6-released

6 Likes

This is really uncomfortable syntax to remember :frowning:

Maybe it helps if you think about it this way:

Html attributes are either static or dynamic.

<div static="…" dynamic={…} />

What you put into static attributes is plain text as is. What you put in dynamic attributes can be any valid elixir expression. This includes, but is not limited to, interpolating something into a string.

3 Likes