[英]How to respond with a stylesheet from your Rails controller?
I have a Rails 5.2.0 api app with a limited set of middleware. 我有一个有限的中间件集的Rails 5.2.0 api应用程序 。 From the app I want to serve a css file to browsers requesting it. 从应用程序中,我想将CSS文件提供给请求它的浏览器。
The content of the css file depends on the request params, so I'd like to be able serve the file from a controller. css文件的内容取决于请求参数,因此我希望能够从控制器提供文件。 I already do this successfully with a script. 我已经使用脚本成功完成了此操作。 Here is my implementation: 这是我的实现:
Rails.application.routes.draw do
get "assets/script" => "assets#script"
get "assets/stylesheet" => "assets#stylesheet", :format => :css
end
class AssetsController < ApplicationController
## This action works
def script
js = ActionController::Base.render(
"assets/script", assigns: {foo: params[:foo]}
)
render :js => js
end
## This action doesn't work
def stylesheet
css = ActionController::Base.render(
"assets/stylesheet", assigns: {foo: params[:foo]}
)
render :plain => css
end
end
When a browser requests the script it becomes available in the browser: 当浏览器请求脚本时,它将在浏览器中可用:
<script>$.getScript("https://example.com/assets/script");</script>
However that is not the case with my stylesheet: 但是我的样式表不是这种情况:
$('<link/>', {
rel: 'stylesheet',
href: "https://example.com/assets/stylesheet.css"
}).appendTo('head');
The stylesheet is returned and added in the browser, but it isn't put to use. 样式表已返回并添加到浏览器中,但尚未使用。 I can serve the exact same content from the /public
folder of a regular Rails app, and it will be put to use. 我可以从常规Rails应用程序的/public
文件夹中提供完全相同的内容,并将其投入使用。
I must be missing something, maybe some response headers. 我必须丢失一些内容,也许有一些响应标题。 Any idea what I'm missing? 知道我缺少什么吗?
Browsers expect css to be served with corresponding content type: 浏览器期望CSS具有相应的内容类型:
render body: css, content_type: 'text/css'
Rails has default mime type for this: render css: css
Rails为此具有默认的mime类型: render css: css
Also you can render in one step: 您也可以一步一步进行渲染:
render template: "assets/stylesheet", formats: [:css], assigns: {foo: params[:foo]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.