Railsのrenderメソッドについて、xml, html, jsonで試してみる
htmlで返す
render html: 'content'
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render html: '<ul><li>hello world</li><li>good bye world</li></ul>' end end
ブラウザ上の表示
あれ。うまく表示されない。
エスケープされてしまっている。
調べるとhtml_safeを用いればhtml要素がエスケープされないらしい。
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render html: '<ul><li>hello world</li><li>good bye world</li></ul>'.html_safe end end
うまくいった。
レスポンスヘッダ
MIMETYPEがtext/htmlになってる。
xmlで返す
render xml: 'content'
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render xml: '<tag>hello world</tg>' end end
ブラウザ上の表示
レスポンスヘッダ
jsonで返す
render json: 'content'
class ApplicationController < ActionController::Base protect_from_forgery with: :exception def hello render json: '{"name": "carotene", "gender": "male"}' end end
ブラウザ上の表示
レスポンスヘッダ