Loading custom CSS in specific template file

Is there any way to load a static CSS in a specific Phoenix template file?

For example, I have the main layout app.html.eex which loads a default /css/app.css and then I want to add another custom CSS only when I load a specific template, like index.html.eex?
I don’t want to add this CSS in layout because it’s being used only on a single page.

I can’t find any info about this in the documentation, so if anybody can help, I’ll be grateful!

3 Likes

Yes, with render_existing/3. Here is an example with css derived from the docs for render_existing/3:

In app.html.eex:

<%= render_existing(@view_module, "styles." <> @view_template, assigns) %>

Now you can achieve this two ways. Either with a function in the view module:

def render("styles.index.html", %{conn: conn}) do
  style = static_path(conn, "/css/custom.css")
  ~E(<link rel="stylesheet" type="text/css" href="#{style}">)
end

or by creating a template called styles.index.html.eex:

<link rel="stylesheet" type="text/css" href="<%= static_path(@conn, "/css/custom.css") %>">
5 Likes

One way to do this which may perform better is to set an id on the body tag for the page in your layout e.g.

id=“page-mycontroller-myaction”

Then you can write CSS rules in a common style sheet which apply to that page, e.g.

#page-mycontroller-myaction h1 {
color: green;
}

By putting everything in a single style sheet, you reduce the number of http requests to the server and make it more cachable.

1 Like

Thanks @voughtdq, this should be what I need.

Thanks for your suggestion @jakemorrison. Reducing the number of requests is something I am looking into and, when possible, trying to put everything together.

In this specific project, I have two themes with two different layouts, an admin and frontend theme, so I am looking for the best way to completely separate their assets and only load what is needed for that specific layout, otherwise it’s too much unnecessary CSS to bundle together.

1 Like