ruby-on-rails - 如何在 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>
但这在我的模板视图中看起来很难看(因为缩进已关闭)。
问题:我怎样才能使<%=
也吞下前导空格?我知道使用-%>
作为结束标签会删除尾随空格/换行符......但我希望前导空格(不仅仅是换行符)也被删除。
解决方案
尝试使用带有以代替开头的 ERB 标记的concat
辅助方法:<%
<%=
<p>
<strong>Code:</strong>
<pre class="highlight github">
<% concat(highlight(@code.code, @code.language)) %>
</pre>
</p>
推荐阅读
- node.js - 满足条件时,Node.js 开关/案例不中断
- python - 调试 Python 脚本时是否可以复制 Jupyter Notebooks 单元的功能?
- iis - 是否可以将 IIS Web 应用程序迁移到 SharePoint?
- r - rmd 将在按下“i”时自动创建代码块
- python - 如何在python中访问嵌套字典中的元素?
- sql - 选择最少两行然后排序(没有完整的分组)
- javascript - 从带有字符串和空格的数组中删除逗号到电子邮件
- go - 在字段名称之前提取 csv 空间
- mysql - MySQL 5.7.25 中 IF NOT EXISTS 的正确语法是什么?
- java - 有人可以解释一下算法吗?