How do I render a partial of a different format in Rails?

前端 未结 11 1251
执念已碎
执念已碎 2020-11-28 04:21

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         


        
11条回答
  •  半阙折子戏
    2020-11-28 04:57

    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.

提交回复
热议问题