nonopolarity
nonopolarity

Reputation: 151036

Can HAML in Ruby on Rails output HTML attributes in an "ordered hash" way?

For example, if using haml:

%html{'xmlns' => "http://www.w3.org/1999/xhtml",
      'xmlns:og' => "http://ogp.me/ns#",
      'xmlns:fb' => "http://www.facebook.com/2008/fbml"}

the output is:

<html xmlns:fb='http://www.facebook.com/2008/fbml' xmlns:og='http://ogp.me/ns#' xmlns='http://www.w3.org/1999/xhtml'> 

which is in a different order. Is there a way to make it in the order that was specified?

(it is using Ruby 1.9.2 and Rails 3.0.6)

Update 1: although in HTML, the attributes' order doesn't matter, but in some case, I just want to follow what the spec says. Who knows what their parser does and whether it uses some regular-expression to do things that people following the spec will match, but not following the spec will not match, because of the "bug" that they use regular-expression to do parsing.

Update 2: Or, what if in the general case for something else? It doesn't need to be HTML attributes. It can be anything of which order is important.

Upvotes: 3

Views: 923

Answers (2)

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79562

I'll point out that arguments in HTML are orderless, so it is quite unclear why you would care about this.

If you really want to keep the order, you could use the alternate HAML syntax:

%html(xmlns="http://www.w3.org/1999/xhtml"
  xmlns:og="http://ogp.me/ns#"
  xmlns:fb="http://www.facebook.com/2008/fbml")

Edit: alternate syntax gives same result. goto "arguments_are_orderless"

Upvotes: 4

Jakob Borg
Jakob Borg

Reputation: 24435

You could, if you generate the actual HTML string yourself from a helper function.

def html_with_ns
  '<html xmlns="...">'
end

and then

=html_with_ns

in the template. Not very attractive, but perhaps that's the price for perfection in this case.

You could argue that this should not be necessary since hashes are actually ordered in Ruby 1.9 (see comments below, I didn't know this was the case). Perhaps a patch for Haml to not sort hashes when running under 1.9 might be in order...

Upvotes: 2

Related Questions