Note that there are some explanatory texts on larger screens.

plurals
  1. POAuto-removing all newlines from Haml output
    text
    copied!<p>I'm using Haml in a Rails 3 app, and its newlines drive me nuts! For example,</p> <pre><code>%span foo </code></pre> <p>renders as</p> <pre><code>&lt;span&gt; foo &lt;/span&gt; </code></pre> <p>But I'd much rather want</p> <pre><code>&lt;span&gt;foo&lt;/foo&gt; </code></pre> <p>The reason (apart from being cleaner XML) is that extra newlines are a problem for my Selenium tests because they mess up the ability to do XPath queries like <code>"//span[.='foo']"</code>. So I'd have to write <code>'\nfoo\n'</code> instead (ew!), or use <code>//span[contains(text(), 'foo')]</code>, which matches too broadly.</p> <p>I know I could use the alligator operators ("&lt;" and ">") to strip whitespace, but since I don't ever have a case where I <em>want</em> the newlines to appear in the output, I'd just end up adding them mechanically at the end of each line. And that just seems very unDRY.</p> <p>So now I see two solutions:</p> <ol> <li>Force Haml to never emit newlines unless they come from a Ruby expression. I see some <code>nuke_inner_whitespace</code> / <code>nuke_outer_whitespace</code> variables spread around the Haml code that might do the job, but I'm not sure how to change them without resorting to gratuitous monkey-patching.</li> <li>Hook into Rails to apply a <code>gsub!("\n", "")</code> to all rendered HTML. (For textarea's and pre's, I could still use <code>~ "foo\nbar"</code> to make Haml emit <code>foo&amp;#x000A;bar</code>.) But where's the right place to hook into Rails? I'm a little lost in the code.</li> </ol> <p>Any pointers or other suggestions appreciated!</p> <p><strong>Update:</strong> I've used Jason's monkey patch below for a while now and I'm beginning to think that it's not worth it. E.g. if I want to get <code>&lt;span&gt;[del]&lt;/span&gt; &lt;span&gt;foo&lt;/span&gt;</code>, it's difficult to <em>not</em> have the blank space in between nuked. Even the following will render as <code>[del]foo</code> on the page:</p> <pre><code>%span = '[del] ' %span foo </code></pre> <p>So I think I'm going back to adding alligator operators manually (see my self-answer down below). Live and learn.</p> <p>Thanks again to Jason! :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload