我正在尝试使用format.js渲染模板,但我使用html格式进行渲染。如果我使用respond to
进行渲染,一切正常,我会渲染js格式。渲染字符串如下所示:
def render_alert(message, opts = {})
locals = opts.slice(:title, :type)
locals[:type] ||= 'info'
locals.merge!(message: message)
render_params = {
partial: 'layouts/alert',
locals: locals
}
render render_params
end
request.format.to_sym显示:js 如果将最后一个字符串改为
,一切运作良好respond_to do |format|
format.js do
render render_params
end
format.html do
render render_params
end
end
任何想法可能出错?请求格式正确无误:
p 'render_params', render_params, request.format.to_sym
render render_params
更新: 如果从控制器调用此函数,一切运行良好,但如果在before_action中从rescue块调用它,则呈现html:
rescue_from CanCan::AccessDenied do |exception|
if request.xhr?
render_alert(exception.message, type: 'error')
else
url = request.referrer
ref_uri = URI.parse(url) rescue nil
url = root_url if url.blank? || ref_uri&.host != request.domain
redirect_to url, :alert => exception.message
end
end
答案 0 :(得分:1)
请尝试将格式传递给渲染方法,如下所示:
locals = opts.slice(:title, :type)
locals[:type] ||= 'info'
locals.merge!(message: message)
render_params = {
partial: 'layouts/alert',
locals: locals
}
render render_params, format: request.format.to_sym
我在这里试试,并且工作正常:D
我的测试代码:
<强>控制器强>
def teste
render_params = {partial: 'layouts/alert', locals: {type: 'error', message: 'You are not authorized to access this page.'}}
render render_params, format: request.format.to_sym
end
查看强>
<强>布局/ _alert.js.erb 强>
alert('<%= message %>');
<强>布局/ _alert.js.erb 强>
<h1><%= message %></h1>
结果JS:
结果HTML: