如何在以`pre`元素结尾的Rails的ERB模板中使用`<%=`修剪前导空格? [英] How to trim leading whitespace with `<%=` in ERB templates in Rails that end up in `pre` elements?

查看:84
本文介绍了如何在以`pre`元素结尾的Rails的ERB模板中使用`<%=`修剪前导空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(据我在这里进行的研究,这不是一个重复的问题。正在以<%-或-来讨论修剪空格(通常在尾随换行符)或-%> ,但不能用于<%= ,这可能是Erubi模板引擎中的次要缺陷,因为

(As far as I have researched here, this is not a duplicate question. Trimming spaces -- often trailing newlines -- is being discussed for <%- or -%>, but not for <%=. It could be a minor defect in Erubi template engine as well, the one being used by Rails for ERB templates.)

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

I want to render / syntax-highlight code in a view, and my ERB view template contains:

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

结果是HTML输出为:

The result is that the HTML output is:

<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中包含了第一行代码前面的内容,并因此进行了渲染,导致第一行代码的缩进量过多了四个空格。

Because of the pre tag, the spaces in front of the first code line are included in the HTML and thus rendered, resulting that the first code line is indented with four spaces too much.

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

Obviously, I can also make the ERB view template as:

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

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

but that looks ugly (because the indenting is off) in my template view.

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

Question: how can I make the <%= also swallow leading spaces? I know that using -%> as closing tag removes trailing spaces/newlines... but I want the leading spaces (not just newlines) to be removed as well.

推荐答案

尝试使用 concat 辅助方法,其ERB标记以开头%而不是<%=

Try using the concat helper method with an ERB tag that starts with <% instead of <%=:

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

这篇关于如何在以`pre`元素结尾的Rails的ERB模板中使用`&lt;%=`修剪前导空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆