如何在 Rails 中呈现不同格式的一部分? [英] How do I render a partial of a different format in Rails?
问题描述
我正在尝试生成包含一些 HTML 的 JSON 响应.因此,我有 /app/views/foo/bar.json.erb
:
I'm trying to generate a JSON response that includes some HTML. Thus, I have /app/views/foo/bar.json.erb
:
{
someKey: 'some value',
someHTML: "<%= h render(:partial => '/foo/baz') -%>"
}
我希望它渲染 /app/views/foo/_baz.html.erb
,但它只会渲染 /app/views/foo/_baz.json.erb
代码>.传递 :format =>'html'
没有帮助.
I want it to render /app/views/foo/_baz.html.erb
, but it will only render /app/views/foo/_baz.json.erb
. Passing :format => 'html'
doesn't help.
推荐答案
基于 roninek 的回应,我发现最佳解决方案如下:
Building on roninek's response, I've found the best solution to be the following:
在/app/helpers/application.rb:
in /app/helpers/application.rb:
def with_format(format, &block)
old_format = @template_format
@template_format = format
result = block.call
@template_format = old_format
return result
end
在/app/views/foo/bar.json:
In /app/views/foo/bar.json:
<% with_format('html') do %>
<%= h render(:partial => '/foo/baz') %>
<% end %>
另一种解决方案是重新定义 render
以接受 :format
参数.
An alternate solution would be to redefine render
to accept a :format
parameter.
我无法让 render :file
与当地人一起工作,而且没有一些路径问题.
I couldn't get render :file
to work with locals and without some path wonkiness.
这篇关于如何在 Rails 中呈现不同格式的一部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!