为什么注释掉的 ERB 仍然会报错?

Why does commented-out ERB still throw errors?

我有一个 HTML 格式的文件:

html
more html
<%= valid erb %>

<!--
  <%= incomplete_erb_with_bugs %>
-->

但由于错误的 ERB,我仍然得到一个异常页面。但是不应该评论该部分导致浏览器无法读取该部分吗?是否还有另一种 HTML 方法可以真正阻止浏览器读取代码?

您正在注释掉 html,但其中的 ruby 代码仍会被评估。你需要注释掉代码,这样做是这样的:

<%#= incomplete_erb_with_bugs %>

您需要注释实际的行,而不是它周围的 html

html
more html
<%= valid erb %>


  <%= incomplete_erb_with_bugs %>

你也可以使用 if 语句

<% if false %>
      <%#= incomplete_erb_with_bugs %>
<% end %>

因为它没有评论。

But shouldn't commenting that section out cause that part not to be read by the browser?

浏览器不执行 Ruby 或 ERB - 服务器在将生成的 HTML 文档发送到浏览器之前执行。

ERB 是 ruby 嵌入在包含文字文本的文件中的代码。除了"erb tags"中的代码,解释器不关心任何东西。

This is just literal text 
<%# this is a ruby line comment - the code below is executed: %>
<% bar do %>
  <%= foo %>
<% end %> 

其余的只是放在缓冲区中。这就像 PHP 或任何其他嵌入式语言一样。

因此,HTML 注释(或 CSS 或 JS)不会以任何方式影响 ERB 解释器。解释器并不真正知道或关心它创建 HTML.

Is there another HTML method for actually preventing the browser from reading code?

浏览器不执行Ruby代码。它只是根据您在响应中发送的任何内容构建一个文档。

所以使用 ruby 注释 <%#= incomplete_erb_with_bugs %> 这将阻止代码被执行 - 它永远不会被发送到浏览器。