问题
(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.)
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>
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>
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.
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.
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.
回答1:
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>
来源:https://stackoverflow.com/questions/53167613/how-to-trim-leading-whitespace-with-in-erb-templates-in-rails-that-end-up