css - 通过通过 #show/n?format=css 而不是 #show/n.css 返回的 Controller 自定义 CSS

标签 css ruby-on-rails ruby-on-rails-3.2

我正在为 Rails 3.2 应用程序实现自定义主题主题,每个主题的 CSS 覆盖数量非常少。

虽然到目前为止我已经通过在布局文件中内联一些 CSS(包括偶尔的 Erb 参数)来实现主题变体,但我真的很想通过 GET 请求提供自定义 CSS 来整理它,例如:(假设current_theme 已定义)

<%= stylesheet_link_tag theme_path(current_theme, format: :css) %>

在我的 themes_controller.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.csstheme_path 生成的 URL 形式助手 – 正在生成 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'

(使用稍微不同的路线,以免与 routes.rb 中的 resources :themes 冲突)。 themestyle_path(current_theme)生成一条可行路线 – /themestyle/1 – 我可以在渲染阶段添加“text/css”类型的 header ,没问题。我将不得不手动编码 <link rel="stylesheet">元素,因为 stylesheet_link_tag 添加了 css 后缀。

最佳答案

我不知道这是否正确,但我看到你的错误是你正在尝试使用 controller action 来完成 helper 的工作

Controller 操作仅在 HTTP 请求时调用,根据我的经验,您不能仅通过从 View /布局链接到它来调用操作——您必须通过后端或通过 ajax 显式调用操作或者什么


把你的行为变成帮助者

<%= stylesheet_link_tag theme(current_theme) %>


#app/controllers/application_controller.rb
def theme
    return theme_path(params[:id])
end
helper_method :theme

我不知道这是否会正确生成路线,但这肯定是我会使用的方法

关于css - 通过通过 #show/n?format=css 而不是 #show/n.css 返回的 Controller 自定义 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767984/

相关文章:

css - Grunt : SASS creates unwanted . map 文件

css - 纸质复选框和 -webkit-column-count

ruby-on-rails - :method put: not working instead Get method

html - 疯狂的硬 CSS 困境

ruby-on-rails - form_for 中的标签

ruby-on-rails - 在 Rails 中使用演示者

javascript - 使输入宽度相同

css - Apache 提供过时的 CSS

sql - 在 UNION ALL View 创建中使用 JOIN

ruby-on-rails - 使用载波图像作为 CSS 背景图像的 Turbolinks