[英]Load different CSS in application layout based on page type (Ruby on Rails)
My application has pages of two basic types: forms and tables. 我的应用程序具有两种基本类型的页面:表单和表格。
As such, I have two different CSS files, forms.css and tables.css. 因此,我有两个不同的CSS文件,即form.css和table.css。
In my application layout file (application.html.erb), I'd like to load different stylesheets depending on some sort of flag set in a given view. 在我的应用程序布局文件(application.html.erb)中,我想根据给定视图中设置的某种标记来加载不同的样式表。
For example, <%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %>
例如, <%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %>
<%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %>
. <%= defined?(@tables) : stylesheet_link_tag 'tables' ? stylesheet_link_tag 'forms' %>
。
The above snippet doesn't actually work, but that's what I'm trying to accomplish? 上面的代码片段实际上不起作用,但这就是我要完成的工作?
Any ideas? 有任何想法吗?
You should move this to a before_filter in your controller. 您应该将其移至控制器中的before_filter。 Keep the view lightweight. 保持视图轻巧。
In the view: 在视图中:
<%=stylesheet_link_tag @foo %>
before_filter in Controller: Controller中的before_filter:
before_filter :get_css_file
def get_css_file
@foo = defined?(@tables) ? 'tables' : 'forms'
end
I presume you set @tables in your controller, so you might have to adjust your logic, but you get the idea. 我假设您在控制器中设置了@tables,因此您可能必须调整逻辑,但是您明白了。 In fact you already know if it's a table or form page controller, probably, so you'd basically just be setting @foo
directly: @foo = 'tables'
etc. 实际上,您可能已经知道它是表控制器还是表单页面控制器,因此您基本上只需要直接设置@foo
: @foo = 'tables'
等。
I've just tried a similar thing and it works for me. 我刚刚尝试了类似的操作,它对我有用。 Your code isn't quite right, perhaps you just need to change it to 您的代码不太正确,也许您只需要将其更改为
<%= stylesheet_link_tag(defined?(@tables) ? 'tables' : 'forms') %>
Your ternary operator syntax is wrong, if that's what you're trying to do. 如果这是您要尝试的操作,那么您的三元运算符语法是错误的。 I think you mean this: 我想你的意思是:
<%= defined?(@tables) ? stylesheet_link_tag 'tables' : stylesheet_link_tag 'forms' %>
The question mark (?) and colon (:) changed places. 问号(?)和冒号(:)更改了位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.