我正在为 Rails 3.2 应用程序实现一个自定义主题问题,每个主题都有少量的 CSS 覆盖。
虽然到目前为止我已经通过在布局文件中内联一些 CSS(包括偶尔的 Erb 参数)来实现主题变体,但我真的很想通过 GET 请求提供自定义 CSS 来整理它,例如:(假设current_theme
已定义)
<%= stylesheet_link_tag theme_path(current_theme, format: :css) %>
在我的主题控制器.rb 中:
class ThemesController < ApplicationController
respond_to :css
...
def show
@theme = Theme.find(params[:id])
respond_with @theme
end
end
我show.css.erb
在views/themes
.
我的主要问题是/themes/1?format=css
正确加载和呈现 CSS 文件。但是,帮助程序/themes/1.css
生成的 URL 形式theme_path
会产生 404。
我可能在这里忽略了一些非常简单的东西——希望一个 SO 用户可以指出明显的绽放,以防止我的头和砖墙变得更好......
更新:做一个 Rails 路线识别调试机器人:
r = Rails.application.routes
#=> #<ActionDispatch::Routing::RouteSet:0x007fc385016170>
r.recognize_path '/themes/1.css'
#=> {:action=>"show", :controller=>"themes", :id=>"1", :format=>"css"}
r.recognize_path '/themes/1?format=css'
#=> {:action=>"show", :controller=>"themes", :id=>"1"}
因此,似乎有效的事实实际上?format=css
是因为,至少在从命令行进行 CURL 时,/themes/1
正在返回必要的 CSS。就我而言,这是一个红鲱鱼......
顺便说一句,将此行添加到routes.rb
作品中:
get '/themestyle/:id' => 'themes#show', as: 'themestyle', format: 'css'
(使用稍微不同的路由,以免与resources :themes
routes.rb 中的冲突)。themestyle_path(current_theme)
生成一个可行的路线/themestyle/1
——我可以在渲染阶段添加'text/css'类型的标题没问题。不过,我必须手动编写一个<link rel="stylesheet">
元素,因为 stylesheet_link_tag 添加了 css 后缀。