How to show static images in a heex template?

I am trying to show a simple static image on a heex template

tried this

<img src={Routes.static_path(@conn, "/images/img1.png")} />

But getting:

function Routes.static_path/2 is undefined (module Routes is not available)

What’s the normal way we could show static images in a page?

Phoenix >= 1.7

If you are using Phoenix 1.7, then you should use verified routes, because Routes helper is removed.

What is the verified routes? In your case, you just write something like:

<img src={~p"/images/img1.png"} />

Read this for more details.

Phoenix < 1.7

If you are using Phoenix <1.7, check if you have something like:

# suppose that the base module of you app is MyApp
alias MyAppWeb.Router.Helpers, as: Routes

I am using Phoenix >= 1.7

When I created the project using mix the assets folder had no “images” folder, so I created it and I put my image there

The following doesn’t show the image:

<img src={~p"/images/img1.png"} />

so I tried

<img src={~p"/assets/images/img1.png"} />

but no luck either

Look at your my_app_web.ex file. It holds a static list of allowed places for static assets (prev. this list was in endpoint.ex with Plug.Static).


I can found this line

def static_paths, do: ~w(assets fonts images favicon.ico robots.txt)

my image is under “assets/images/img1.png”

but still doesn’t show up using

<img src={~p"/assets/images/img1.png"} />

So in your project it needs to be in /priv/static/images/… and the route will be /images/… or /priv/static/assets/images/…/assets/images/…. Which one of these matches with what you have?


Do you mean that I have put the image in priv folder (priv/static/images) isn’t that folder supposed to not be touched?

I am getting confused because at the root of the app there is an “assets” folder with css and js and I thought this is where should I put images too.

Phoenix 1.6 and the change to esbuild removed the handling of static assets between assets and /priv/static. Only /priv/static/assets has generated files (js/css), all other things in there you can maintain where they are.


OK, as confusing as it sounds here is what the doc is saying:

assets - a directory that keeps source code for your front-end assets, typically JavaScript and CSS. These sources are automatically bundled by the esbuild tool. Static files like images and fonts go in priv/static

I am not very fun of putting things here and there, but this is how they decided to put it :face_with_raised_eyebrow:

1 Like

You made my day :slight_smile: :partying_face: :pray: :+1: I was wondering why some files were still being served without any Plug.Static configuration in router.ex and the user not being authenticated. :sweat_smile: