How to trim leading whitespace with `<%=` i

2019-07-20 09:33发布

问题:

(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>