Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use rails stylesheet_link_tag based on path || controller?

In my application layout I have this conditional which helps deciding what stylesheet to use based on existence of current_user:

<% if current_user %>
  <%= stylesheet_link_tag 'application', media: 'all', id: "maincss" %>
<% else %>
  <%= stylesheet_link_tag 'session', media: 'all', id: "maincss" %>
<% end %>

But how can I specify which stylesheet to use based on the url?

For example, I want to use a 'password_reset.css' file for this path

get '/set/:password_reset_token' => 'password_resets#edit'
like image 649
Bogdan Popa Avatar asked May 02 '26 19:05

Bogdan Popa


2 Answers

Here is what I do in my projects:

In the layout file, add a yield method like this:

<html>
  <head>
    ...
    ...
    <%= yield(:head) %>
  </head>
  ...

In any view page (.erb file) that needs a custom CSS, I would add something like this at the top of the page.

 <% content_for :head do %>
   <%= stylesheet_link_tag 'custom_css_filename', media: 'all' %>
 <% end %>

This way stylesheet will go in the right place only for that page.

Note:

If you want to include a custom stylesheet for every single URL in your application, you should use what is suggested in the previous answer.

like image 185
San Avatar answered May 05 '26 09:05

San


You can try using

<%= stylesheet_link_tag *([params[:controller], params[:action]] + (params[:id] || '').split('/')) %>

If you are okay with using password_resets.css instead of password_reset.css

Note: You may get a few unwanted link tags as well, which may result in harmless(except to logs) 404 responses

like image 25
TMaYaD Avatar answered May 05 '26 10:05

TMaYaD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!