首页 > 解决方案 > 如何在 Rails 的 ERB 模板中使用 `<%=` 修剪前导空格,最终以`pre` 元素结束?

问题描述

(据我在这里研究过,这不是一个重复的问题。正在讨论修剪空格 - 通常尾随换行符 -<%--%>,但不是<%=。这也可能是 Erubi 模板引擎中的一个小缺陷,一个Rails 将其用于 ERB 模板。)

我想在视图中呈现/语法高亮代码,我的 ERB 视图模板包含:

<p>
  <strong>Code:</strong>
  <pre class="highlight github">
    <%= highlight(@code.code, @code.language) %>
  </pre>
</p>

结果是 HTML 输出为:

<p>
  <strong>Code:</strong>
  <pre class="highlight github">
    <span class="kt">[and here's the code, but indented too much]</span>
  </pre>
</p>

由于pre标签的原因,第一行代码前面的空格被包含在HTML中并因此被渲染,导致第一行代码缩进四个空格过多。

显然,我也可以将 ERB 视图模板制作为:

<p>
  <strong>Code:</strong>
  <pre class="highlight github">
<%= highlight(@code.code, @code.language) %>
  </pre>
</p>

但这在我的模板视图中看起来很难看(因为缩进已关闭)。

问题:我怎样才能使<%=也吞下前导空格?我知道使用-%>作为结束标签会删除尾随空格/换行符......但我希望前导空格(不仅仅是换行符)也被删除。

标签: ruby-on-railserbactionviewerubis

解决方案


尝试使用带有以代替开头的 ERB 标记的concat辅助方法<%<%=

<p>
  <strong>Code:</strong>
  <pre class="highlight github">
    <% concat(highlight(@code.code, @code.language)) %>
  </pre>
</p>

推荐阅读