Bloquear comentarios en html.plantillas erb en rails


¿Cómo comentar html mezclado con código ruby?

some text <% ... %> more text <%= ... %>
something else
<% ... %>

En jsp es muy simple: <%-- ... --%>, pero no puedo encontrar ninguna opción concisa en rails.

Los comentarios html simples <!-- ... --> no funcionan: el código ruby todavía se ejecuta y grita errores.

Hay una opción para usar if false con comentarios html, pero es bastante detallada, por no mencionar que IDEs no lo soporta.

También hay una opción que viene de pure ruby, que sorprendentemente funciona.

<%
=begin %>
... html and ruby code goes here
<%
=end %>

Es generalmente bien, excepto que es verboso, de aspecto extraño y ninguno de los IDEs de Ruby que conozco lo soportan (sí, me gusta comentar/comentar con una sola pulsación de tecla).

Tengo curiosidad, ¿hay algún 'oficial' de hacer esto en rails?

Gracias!

Author: Nikita Rybak, 2010-06-27

15 answers

No contaría como una solución, pero quizás encerrando el trozo entre un

<% if false %>
   ...
<% end %>

O si se siente un poco sucio, cree un ayudante que simplemente no genere nada.

Nunca lo he necesitado, pero me tropecé con que parece que no hay una solución lista para usar para esto.

 104
Author: Chubas,
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-07-23 16:14:01

Use esto para comentar líneas individuales:

<%# your_ruby_code %>

Para múltiples líneas, el

<% 
=begin %>  <% ruby_code %>
<% 
=end %>

Lo que dijiste funcionaría.

 147
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-27 16:53:42

El enfoque =begin es molesto porque:

  1. No funciona para HTML mixto y Ruby (o simplemente HTML) que está en una sola línea
  2. Es molesto escribir

El enfoque <% if false %> funciona, pero se ve raro y no le da a nadie más que mire su código una pista sobre sus intenciones.

Mi solución es la siguiente:

{[6] {} En[4]}, agregue un método así:
def comment
end

Luego en tu plantilla de vista, puedes decir:

<% comment do %>Some stuff that won't be rendered...<% end %>

Esto funciona porque cualquier El método Ruby puede tomar un bloque, pero ignorará silenciosamente el bloque pasado si su método no incluye un yield.

 21
Author: sumizome,
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-10 00:29:01

Dado que puedes usar <% %> para poner un bloque ruby, ciertamente se puede usar para poner comentarios en él.

Se vería como una solución más simple y elegante...

<%
# See! I am a Ruby Comment
# And I am multi-line
# I look like a recognizable ruby comment block too
# and not so complex
# The only drawback with me is the Hash symbol you have to repeat
# But it's the norm, isn't it?
%>
 8
Author: Sagar Ranglani,
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-08-30 12:20:12

Para los comentarios de bloque en las plantillas, mi editor de texto (Komodo) encuentra esta variación en la recomendación de@Garfield menos desagradable:

<%# A long multiline comment in a rails template ...
  # line 2
  # and so on ... 
  # %>
 7
Author: klenwell,
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 11:47:29
<%#=

...commented
multiline
block...

%>
 7
Author: Piotr Turek,
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-09 10:07:03

Para comentar las etiquetas erb use el símbolo de hash ruby comment antes del signo = en la etiqueta de apertura

<p>
 This is some text I want to keep
 <%= @some_object.some_attribute %>
</p>
<p>
  I want to keep this text but comment out the erb tag
  <%#= @some_object.another_attribute %>
</p>
<!--
<p>
  I want all of this text commented out including the erb tag
  <%#= @some_object.some_attribute %>
</p>
-->
<!--
<p>
 I just want this html commented out but I want to keep the erb tag
 <%= @some_object.some_attribute %>
</p>
-->
 6
Author: jamesw,
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-07-23 16:34:19

After = begin no es necesario poner % >

<%
=begin

code code code code code code 
code code code code code code 
code code code code code code 
code code code code code code 

=end %>
 4
Author: Michal,
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
2016-02-15 13:39:02

Hay que tener en cuenta dónde se ejecuta el código. Los comentarios estilo Ruby funcionan porque el código Ruby se ejecuta en el servidor antes de ser servido al navegador web. Esto también explica por qué los comentarios HTML no funcionan-el Ruby ya ha sido ejecutado.

¿El IDE que está utilizando no admite la creación de macros personalizadas para comentar bloques de código?

 1
Author: John Topley,
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-27 16:02:20

El atajo de bloque de comentario de Sublime Text ctrl+shift+/ observa si ha seleccionado HTML normal o una etiqueta Erb y coloca <!--- o <% =begin %> en consecuencia.

 1
Author: iono,
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-12-11 21:46:54

Este es el único que trabajó para mí.

<%
=begin %>

code code code code code code 
code code code code code code 
code code code code code code 
code code code code code code 

=end %>
 0
Author: Platon,
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
2016-02-08 13:38:17

Solo una adición a algunas de las respuestas anteriores. Encontré la solución = begin / = end más útil, pero por el bien de la belleza la escribo así:

<%
=begin
  <p>HTML will be ignored</p>
  <%= 'and so will ruby' %>
  <p>
    <%= 'plus the whole block will be greyed in editor' %>
  </p>
=end
%>

Tenga en cuenta que ya que todo se ignora hasta el =end no hay necesidad de cerrar la etiqueta =begin con %> o abrir la etiqueta =end con <% (que también se ha señalado en una respuesta anterior)

Encontré que esta es la solución más elegante para superar por completo un bloque de código ruby y html mixto y tenerlo gris en mi editor también, a diferencia de la solución <% if false %>. El único inconveniente es que =begin y =end deben colocarse al principio de la línea..

 0
Author: ViggoV,
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
2018-05-22 13:00:43

Puede usar y comentarios HTML al mismo tiempo:

<%if false%><--

stuff to comment out

--><%end%>

Los beneficios son:

  • El código Ruby no se ejecuta

  • El bloque comentado tiene color gris en IDE

  • La intención es obvia para otros desarrolladores

 0
Author: stillwaiting,
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
2018-05-23 23:08:37

Use un HEREDOC llamado comentario

Ventajas:

  • Se explica por sí mismo que esto es un comentario
  • Funciona para etiquetas erb y HTML
  • Tiene resaltado de sintaxis ok (como una cadena larga)

Contras:

  • Extraña sintaxis de cierre de 3 líneas
  • Sin atajos de teclado

Código:

La etiqueta de apertura puede ser

<% <<-COMMENT %>

the above closing erb tag is just for looks (to match the end),
but don't put anything else there, it may show up on the page

O

<%
<<-COMMENT
%>

Nada aquí no se ejecutará ni se mostrará en el navegador

<P>
    this will not be displayed in the browser
    <strong> even in the developer's tools </strong>
</p>

<% 1_000_000_000_000.times do |count| %>

for the <%= count %>'th time, this won't run a trillion times,
this is all just a string

all of these %>, <%, <% end %>, end, do, <!--, won't cause any issues.

but the below opening erb tag is important (if you used any erb tags in the comment).
I have no clue why?

El cierre tag

Sí, tiene que ser de 3 líneas . No se por qué la etiqueta erb de apertura es importante, pero lo es! (a menos que no hayas usado ninguna etiqueta erb en el comentario).

<%      
COMMENT
%>
 0
Author: Arye Dov Eidelman,
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
2018-07-08 21:59:27

La única solución aceptable que encontré para este problema agotador fue poner un espacio dentro del "

Así:

<!--
<p>
  < %= @some_object.some_attribute %>
</p>
<p>
  < %= @some_object.another_attribute %>
</p>
<p>
  < %= @some_object.some_attribute %>
</p>
<p>
  < %= @some_object.some_attribute %>
</p>
-->

Sí, agregar los espacios es molesto. Pero es la menos molesta de todas las soluciones que he visto.

 -4
Author: ineedahero,
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
2016-11-03 20:15:56