yegor256
yegor256

Reputation: 105213

How to render a variable in HAML and preserve white-spaces?

This is what I'm doing:

%pre
  =var

The value of var is "foo\nbar". I'm getting this HTML:

<body>
  <pre>foo
  bar</pre>
</body>

Obviously, I'm expecting:

<body>
  <pre>foo
bar</pre>
</body>

What to do?

Upvotes: 1

Views: 475

Answers (2)

matt
matt

Reputation: 79813

If you use ugly mode then you shouldn’t have this problem. Note that in (the hopefully coming soon) Haml 5 there only is ugly mode, so this is probably the best option for the future.

This would produce:

<body>
<pre>foo
bar</pre>
</body>

For current versions, in non-ugly mode, if you wanted to preserve whitespace like this then normally you would use ~, which would call find_and_preserve on the result. However here you are already in a pre block, and so that won’t work (arguably this is a bug, but with the removal of non-ugly mode in Haml 5 I can’t see any benefit of fixing it).

You could use preserve directly though:

%body
  %pre
    =preserve(var)

This produces:

<body>
  <pre>foo&#x000A;bar</pre>
</body>

which has the same affect as your desired result when rendered.

Upvotes: 1

Max Bugaenko
Max Bugaenko

Reputation: 21

You have to place your var on the same line where your %pre is. So it looks like %pre= var

Upvotes: 1

Related Questions