Passing a variable string to a tag value

Hello, so I’m trying to load images using the username of each post as part of the route where the profile pictures are, basically it’s this format.

assets/profilepics/username.png

I tried doing it like this <img src=“static_path(@conn, “/assets/profilepics/#{@posts.user.name}.png”) %>”></img>, but it didn’t do the trick. What would be the correct way to add the username to the section of the tag that requires it?

For you see any errors or what do you see instead of the username in the generated HTML?

Also you haven’t <%= in your post, is that by accident or in your code as well?

In my code as well, I tried doing it with <%= as well but it still shows up as a broken image. And no error per se, just the broken image icon instead of the image in the path.

Also, I do show the user name in one of the posts sections, and it’s loaded fine, so the path not loading fine has to do with my syntax for the img src tag. I’m just not sure where, this is my first project with Phoenix/elixir and I’ve been having some troubles with syntax/logic while working on it.

Then please tell us how the generated HTML looks like. The syntax looks fine assuming you open the <%= correct.

<img src="static_path(@conn, " assets="" profilepics="" #{@posts.user.username}.png")%="">

It looks like this without the <%=, if I add the <%= I get an incomplete expression error.

== Compilation error in file web/views/thread_view.ex ==
** (TokenMissingError) web/templates/thread/show.html.eex:39: syntax error: expression is incomplete
(eex) lib/eex/compiler.ex:45: EEx.Compiler.generate_buffer/4
(eex) lib/eex/compiler.ex:54: EEx.Compiler.generate_buffer/4
(phoenix) lib/phoenix/template.ex:378: Phoenix.Template.compile/2
(phoenix) lib/phoenix/template.ex:186: anonymous fn/3 in Phoenix.Template.“MACRO-before_compile”/2
(elixir) lib/enum.ex:1899: Enum."-reduce/3-lists^foldl/2-0-"/3
(phoenix) expanding macro: Phoenix.Template.before_compile/1
web/views/thread_view.ex:1: Forum.ThreadView (module)
(elixir) lib/kernel/parallel_compiler.ex:198: anonymous fn/4 in Kernel.ParallelCompiler.spawn_workers/6

And how exactly does the code look like that generates this error and the wrong output? The first output clearly shows you are not using <%=, the error shows you are using it probably wrong.

<%=img src="static_path(@conn, "/assets/profilepics/#{@posts.user.username}.png")%>"> This would be the code that generates the error.

Only the elixir stuff needs to be in <%= %>:

<img src="<%= static_path(@conn, "/assets/profilepics/#{@posts.user.username}.png") %>">

On a first glance at least…

3 Likes

Sweet! That did it. Now the HTML looks like this <img src="/assets/profilepics/pmgbove.png">, still shows up a broken image icon but I’ll figure that one out. Thanks a lot!

<img src={image_url}>
thats how it worked for me

This is the syntax in HEEx, that is new in Phoenix LiveView. The old posts are describing plain EEx.

4 Likes