[英]Rails 5 API - How to respond with HTML on a specific controllers as an exception?
我有Rails API應用程序。 並且99%的路由是JSON路由。 但是,我想添加一條將用HTML響應的路由。 我怎樣才能做到這一點?
這是我當前的設置,當我瀏覽路線時,在屏幕上看到一串HTML標簽。
class ApplicationController < ActionController::API
include ActionController::MimeResponds
end
class DocumentPublicController < ApplicationController
respond_to :html
def show
html = "<html><head></head><body><h1>Holololo</h1></body></html>"#, :content_type => 'text/html'
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
end
end
有任何想法嗎?
根據版式和渲染指南 :
當使用html:選項時,如果使用html_safe方法將該字符串未標記為HTML安全,則HTML實體將被轉義。
因此,您只需要告訴它可以安全地呈現為html的字符串即可:
# modified this line, though could be done in the actual render call as well
html = "<html><head></head><body><h1>Holololo</h1></body></html>".html_safe
respond_to do |format|
format.html {render html: html, :content_type => 'text/html'}
end
大多數新API只需要提供JSON,但在API控制器中通常看到respond_to
。 這是一個例子:
def show
html = "<html><head></head><body><h1>Holololo</h1></body></html>"
respond_to do |format|
format.html { render :json => html }
end
end
我們可以刪除respond_to
,但是如果您在不帶.json的情況下訪問url,則會看到它以為您在日志中使用HTML
Processing by PeopleController#index as HTML
如果您希望您的路線以HTML格式進行響應,則可以將其默認設置為HTML
namespace :api, :defaults => {:format => :html} do
namespace :v1 do
resources :people
end
end
因此,您可以放下respond_to
並使其具有詛咒,然后默認將您的路由作為HTML生效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.