How to serve an img with Phoenix?

I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here is what my /web/templates/page/index.html.eex looks like:

<div class=whitext>
  <h2><%= gettext ">>> %{name}", name: "CRVM" %></h2>
  <p> A new perspective on fixed income relative value.</p>
</div>

<div>
  <p> hello </p>
  <img src="/web/static/assets/images/crvmlogowhite.svg"/>
</div>

But nothing is showing up (though “hello” is). So a) what is the canonical way of putting an image onto a page in Elixir, and b) if the above is okay, how is the image referenced? By the way I have tried multiple versions of the path. If I use it as a css background then url("/images/crvmlogowhite.svg") does work.

3 Likes

Your static assets can be served by using the static_path routes. You’ll want to use src instead of source attribute for the file source for your image. But here’s how it should look:

<img src="<%= static_path(@conn, "/images/crvmlogowhite.svg") %>">

Keep in mind with the default configuration of brunch, your asset files are copied to priv/static/ and are served from there. Your endpoint.ex file defines what static files should be served from that directory.

5 Likes

How do you rewrite the following CSS:

background: url('priv/static/assets/images/photo.jpg');

using static_path?

Everything under priv/static is served from /. To link to priv/static/images/photo.jpg in CSS you write url(/images/photo.jpg).

You don’t need to use static_path obligatory. If you are configuring to serve assets from a CDN, then yes, you would need to simplify the development process.

6 Likes

Thanks, that solved things for me.

I have created a router for this resource and it works fine when get
directly.

Are you serving it with the correct mime-type?