Proper way to load static url from asset folder

Hi ! (Using Phoenix 1.7.11)

I want to load an image I saved in my “static/images” folder from the “app.css” in “/assets” folder.

In templates, I know there is the sigil ~p which allows to simply do:
<img src={~p"/images/logo.png"} />

But how about assets folder ? Is there something special to do to get the proper url of my image ?

I haven’t seen anything in the documentation about that issue.

If you want the path outside your template, there is Application.app_dir(:my_app) for all Elixir applications, not just Phoenix.

Edit: Your .assets/ directory will get copied to ./priv/static/assets on compilation, so you should be able just use {~p"/assets/css/whatever.css"} in your template.

How would I put this inside my app.css file ?

If you want to include your custom CSS file, you should be able to just add an @import.

If you want to reference an image in your CSS, try to add the relative path /images/... directly in CSS. The ~p sigil does nothing special to the path itself, it is a compile time helper that will check if the given path will resolve to something. If you add just a relative path to your CSS, you will miss out on the compile time check, but it should work.

What I came up is simply adding my style in the style attribute for specific items in the heex template file.

<div style={"background-image: url(#{~p"/images/background.png"});"}>My text</div>