How to trim leading whitespace with `<%=` in ERB templates in Rails that end up in `pre` elements?

自古美人都是妖i 提交于 2019-12-23 18:34:24

问题


(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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!