I\'m trying to generate a JSON response that includes some HTML. Thus, I have /app/views/foo/bar.json.erb
:
{
someKey: \'some value\',
someH
In Rails 3, the View has a formats array, which means you can set it to look for [:mobile, :html]. Setting that will default to looking for :mobile templates, but fall back to :html templates. The effects of setting this will cascade down into inner partials.
The best, but still flawed way, that I could find to set this was to put this line at the top of each full mobile template (but not partials).
<% self.formats = [:mobile, :html] %>
The flaw is that you have to add that line to multiple templates. If anyone knows a way to set this once, from application_controller.rb, I'd love to know it. Unfortunately, it doesn't work to add that line to your mobile layout, because the templates are rendered before the layout.
You have two options:
1) use render :file
render :file => "foo/_baz.json.erb"
2) change template format to html by setting @template_format variable
<% @template_format = "html" %>
<%= h render(:partial => '/foo/baz') %>
It seems that passing a formats
option will render it properly in newer Rails version, at least 3.2:
{
someKey: 'some value',
someHTML: "<%= h render('baz', formats: :html) -%>"
}
I came across this thread when I was trying to render an XML partial in another xml.builder view file. Following is a nice way to do it
xml.items :type => "array" do
@items.each do |item|
xml << render(:partial => 'shared/partial.xml.builder', :locals => { :item => item })
end
end
And yeah... Full file name works here as well...
Rails 4 will allow you to pass a formats parameter. So you can do
render(:partial => 'form', :formats => [:html])}
Note you can do something similar in Rails 3 but it wouldn't pass that format to any sub partials (if form calls other partials).
You can have the Rails 4 ability in Rails 3 by creating config/initializers/renderer.rb:
class ActionView::PartialRenderer
private
def setup_with_formats(context, options, block)
formats = Array(options[:formats])
@lookup_context.formats = formats | @lookup_context.formats
setup_without_formats(context, options, block)
end
alias_method_chain :setup, :formats
end
See http://railsguides.net/2012/08/29/rails3-does-not-render-partial-for-specific-format/