newpain01
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!
Most Liked
voughtdq
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") %>">
jakemorrison
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.
newpain01
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









