简体   繁体   English

使用基于路径的 rails stylesheet_link_tag || 控制器?

[英]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:在我的应用程序布局中,我有这个条件,它有助于根据 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?但是如何根据 url 指定要使用的样式表?

For example, I want to use a 'password_reset.css' file for this path例如,我想为此路径使用“password_reset.css”文件

get '/set/:password_reset_token' => 'password_resets#edit'

Here is what I do in my projects:这是我在我的项目中所做的:

In the layout file, add a yield method like this:在布局文件中,添加如下的yield方法:

<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.在任何需要自定义 CSS 的视图页面(.erb 文件)中,我都会在页面顶部添加类似的内容。

 <% 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.如果您想为应用程序中的每个 URL 包含一个自定义样式表,您应该使用上一个答案中的建议。

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如果您可以使用password_resets.css而不是password_reset.css

Note: You may get a few unwanted link tags as well, which may result in harmless(except to logs) 404 responses注意:您也可能会收到一些不需要的链接标签,这可能会导致无害的(日志除外)404 响应

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM