¿Cómo obtengo un parcial de un formato diferente en Rails?


Estoy tratando de generar una respuesta JSON que incluya algo de HTML. Por lo tanto, tengo /app/views/foo/bar.json.erb:

{
  someKey: 'some value',
  someHTML: "<%= h render(:partial => '/foo/baz') -%>"
}

Quiero que render /app/views/foo/_baz.html.erb, pero solo render /app/views/foo/_baz.json.erb. Pasar :format => 'html' no ayuda.

Author: James A. Rosen, 2008-12-04

11 answers

Comenzando con Rails 3.2.3, al llamar a render: uso parcial

:formats => [:html]

En lugar de

:format => 'html'
 97
Author: Tim Haines,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-11 19:36:32

¿Qué hay de malo en

render :partial => '/foo/baz.html.erb'

? Acabo de probar esto para renderizar un parcial ERB HTML desde dentro de una plantilla Atom Builder y funcionó bien. No se requiere jugar con variables globales (sí, sé que tienen "@" delante de ellos, pero eso es lo que son).

Su with_format &block approach es genial, sin embargo, y tiene la ventaja de que solo se especifica el formato, mientras que el enfoque simple especifica el motor de plantillas (ERB/builder/etc) también.

 64
Author: Sam Stokes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:10

Para Rails 3, el bloque with_format funciona, pero es un poco diferente:

  def with_format(format, &block)
    old_formats = formats
    self.formats = [format]
    block.call
    self.formats = old_formats
    nil
  end
 32
Author: zgchurch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-10 13:11:56

Basándose en la respuesta de roninek , he encontrado la mejor solución para ser la siguiente:

En /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

En /app/views/foo/bar.json:

<% with_format('html') do %>
  <%= h render(:partial => '/foo/baz') %>
<% end %>

Una solución alternativa sería redefinir render para aceptar un parámetro :format.

No pude conseguir render :file para trabajar con los locales y sin algún camino torpe.

 29
Author: James A. Rosen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:02:34

Rails 4 le permitirá pasar un parámetro formats. Así que usted puede hacer

render(:partial => 'form', :formats => [:html])} 

Tenga en cuenta que puede hacer algo similar en Rails 3, pero no pasaría ese formato a ningún sub-parcial (si form llama a otros parciales).

Puede tener la habilidad Rails 4 en Rails 3 creando 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

Véase http://railsguides.net/2012/08/29/rails3-does-not-render-partial-for-specific-format /

 29
Author: DrewB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-15 18:50:19

En Rails 3, la vista tiene una matriz de formatos, lo que significa que puede configurarla para buscar [:mobile, :html]. Configuración que por defecto buscará: plantillas móviles, pero volver a: plantillas html. Los efectos de establecer esto caerán en cascada en parciales interiores.

La mejor manera, pero aún defectuosa, que pude encontrar para establecer esto fue poner esta línea en la parte superior de cada plantilla móvil completa (pero no parciales).

<% self.formats = [:mobile, :html] %>

El defecto es que tienes que añadir esa línea a múltiples plantilla. Si alguien conoce una forma de establecer esto una vez, desde application_controller.rb, me encantaría saberlo. Desafortunadamente, no funciona agregar esa línea a su diseño móvil, porque las plantillas se representan antes del diseño.

 24
Author: Tony Stubblebine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-30 23:17:55

Simplemente desarrollando lo que zgchurch escribió:

  • teniendo en cuenta las excepciones
  • devolviendo el resultado del bloque llamado

Pensé que podría ser útil.

def with_format(format, &block)
  old_formats = formats
  begin
    self.formats = [format]
    return block.call
  ensure
    self.formats = old_formats
  end
end
 16
Author: viphe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-22 04:49:00

Tienes dos opciones:

1) use render: file = > " foo / _baz.json.erb "

2) cambie el formato de plantilla a html configurando la variable @template_format

<% @template_format = "html" %>
<%= h render(:partial => '/foo/baz') %>
 9
Author: roninek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-12-04 11:54:01

Tenía un archivo llamado 'api/item.rabl ' y quería renderizarlo desde una vista HTML, así que tuve que usar:

render file: 'api/item', formats: [:json]

(file porque el archivo no tiene guion bajo en el nombre, formats y no format (y pasa y matriz))

 5
Author: Dorian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-18 18:57:29

Parece que pasar una opción formats lo renderizará correctamente en la versión más reciente de Rails, al menos 3.2:

{
  someKey: 'some value',
  someHTML: "<%= h render('baz', formats: :html) -%>"
}
 2
Author: Mario Uher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-22 07:56:06

Me encontré con este hilo cuando estaba tratando de renderizar un XML parcial en otro xml.archivo de vista del constructor. Seguir es una buena manera de hacerlo

xml.items :type => "array" do
    @items.each do |item|
        xml << render(:partial => 'shared/partial.xml.builder', :locals => { :item => item })
    end
end

Y sí... El nombre completo del archivo también funciona aquí...

 1
Author: Garfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-23 09:44:19