Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to I have several haml lines appear on the same line?

Tags:

ruby

haml

I have the following haml:

  9       %strong Asked by:   
 10       = link_to @user.full_name, user_path(@user)     
 11       .small= "(#{@question.created_at.strftime("%B %d, %Y")})" 

This currently puts the link and the date on separate lines, when it should look like "link (date)" and date has a class span of small.....

like image 444
Satchel Avatar asked Apr 26 '11 16:04

Satchel


2 Answers

Your code will generate something like this html:

<strong>Asked by:</strong>
<a href="userpath">User name</a>
<div class='small'>April 26, 2011</div>

When you use something like .small (i.e. use the dot without specifying the element type) haml creates an implicit div. Since div elements are by default block level elements the date will be in a new block and so will appear on a new line. In order to get it to appear on the same line, you'll need an inline level element.

You could change the css for the "small" class to explicitly make it display inline, but html already provides an inline version of the div - the span, so you can change the last line from

.small= "(#{@question.created_at.strftime("%B %d, %Y")})" 

to

%span.small= "(#{@question.created_at.strftime("%B %d, %Y")})" 

which will give you

<strong>Asked by:</strong>
<a href="userpath">User name</a>
<span class='small'>April 26, 2011</span>

which are all inline elements, so will appear as one line.

As for having it all on the same line in the haml, I don't think that's possible with plain haml syntax. Haml uses the indentation and whitespace in order to determine what to do, and having just one line means there's no indentation.

The haml FAQ says:

Expressing the structure of a document and expressing inline formatting are two very different problems. Haml is mostly designed for structure, so the best way to deal with formatting is to leave it to other languages that are designed for it.

You seem to be at the edge of what haml is intended for. You could write your html directly if you really wanted it all on one line:

<strong>Asked by:</strong> #{link_to @user.full_name, user_path(@user)} <span class="small">(#{@question.created_at.strftime("%B %d, %Y")})</span>

or perhaps you could create a helper that will generate the block for you.

like image 188
matt Avatar answered Nov 03 '22 01:11

matt


To make it show up on the same line in the browser, use %span.small, as in the comment above.

To make it all on one line in the HTML output, you will need to use the whitespace removal syntax in Haml. Please understand that newlines in the HTML output do not effect the arrangement of text in the browser.

like image 43
Austin Taylor Avatar answered Nov 03 '22 00:11

Austin Taylor