如何在Rails中呈现不同格式的部分内容? [英] How do I render a partial of a different format in Rails?
本文介绍了如何在Rails中呈现不同格式的部分内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
/app/views/foo/bar.json.erb
: {
someKey:'some value',
someHTML:<%= h render(:partial =>'/ foo / baz') - %>
$ / code $ / pre
$ b $ p我希望它呈现 / app / views / foo / _baz.html.erb
,但它只会呈现 /app/views/foo/_baz.json.erb
。传递:format => 'html'
没有帮助。解决方案建立在罗林内克的回应,我发现最好的解决方案在/app/helpers/application.rb中:
def with_format(format,&block)
old_format = @template_format
@template_format = format
result = block.call
@template_format = old_format
返回结果
end
在/app/views/foo/bar.json: <%with_format('html')do%>
<%= h render(:partial =>'/ foo / baz')%>
<%end%>
另一个解决方案是重新定义 render 接受:format
参数。
我无法得到 render:file
可以和当地人一起工作,而且不需要一些路径。
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') -%>"
}
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.
解决方案 Building on roninek's response, I've found the best solution to be the following:
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
In /app/views/foo/bar.json:
<% with_format('html') do %>
<%= h render(:partial => '/foo/baz') %>
<% end %>
An alternate solution would be to redefine render
to accept a :format
parameter.
I couldn't get render :file
to work with locals and without some path wonkiness.
这篇关于如何在Rails中呈现不同格式的部分内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文