In my Rails template, I\'d like to accomplish final HTML to this effect using HAML:
I will first link somewhere
Alright, here's the solution I'm settling on:
def one_line(&block)
haml_concat capture_haml(&block).gsub("\n", '').gsub('\\n', "\n")
end
I will first
- one_line do
= link_to 'link somewhere', 'http://example.com'
- if @condition
, then render this half of the sentence
\\n
if a condition is met
That way, whitespace is excluded by default, but I can still explicitly include it with a "\n" line. (It needs the double-backslash because otherwise HAML interprets it as an actual newline.) Let me know if there's a better option out there!
Once approach I've taken to this sort of thing is to use string interpolation:
I will first #{link_to 'Link somewhere'}#{', then render this half of the sentence if a condition is met' if condition}
I don't like the look of the literal string in the interpolation, but I've used it with previously declared strings or dynamically generated strings before.
There's the angle bracket "whitespace munching" syntax, otherwise write a helper method for it.
I came across a similar problem and found this so I thought I would post another solution which doesn't require a helper method. Use Ruby interpolation #{} to wrap the link and if statements:
I will first
#{link_to 'link somewhere', 'http://example.com'}#{if true : ", then render this half of the sentence if a condition is met" end}
This works in 3.0.18, it may also work in earlier releases.
You can do this to keep the leading space:
%a{:href => 'http://example.com'}>= ' link somewhere'
The space is in the quotes.
You can also do this using Haml's "trim whitespace" modifier. Inserting >
after a Haml declaration will prevent whitespace from being added around it:
I will first
%a{:href => 'http://example.com'}> link somewhere
- if @condition
, then render this half of the sentence if a condition is met
produces:
I will first<a href='http://example.com'>link somewhere</a>, then render this half of the sentence if a condition is met
However, as you can see, the >
modifier also strips the whitespace in front of the link, removing the desired space between the words and the link. I haven't figured a pretty way around this yet, except to add
to the end of "I will first", like so:
I will first
%a{:href => 'http://example.com'}> link somewhere
- if @condition
, then render this half of the sentence if a condition is met
Which finally produces the desired output without lots of hard-to-read interpolation:
I will first <span><a href="http://example.com">link somewhere</a></span>, then render this half of the sentence if a condition is met