31

How can I convert this line

  <body data-spy="abcd">

to HAML syntax?

This one returns me an error

  %body{:data-spy => "abcd"}
user984621
  • 46,344
  • 73
  • 224
  • 412

3 Answers3

38

HAML Syntax for the HTML5 Data Field:

%div{ :data => {:id => '555'} }

Now, I started messing around, and it looks like this only works with "data" -- other tags need to be:

%div{ "star-datas" => "hello!" }

Your example:

%body{:data => { :spy => 'abcd'}}
CrazyVipa
  • 927
  • 7
  • 10
  • Ran into a problem using this syntax, because I needed "data-0" and :0 isn't a valid symbol, so I changed my syntax to `:data => {'spy' => 'abcd'}` – Christos Hrousis Jun 16 '14 at 05:29
  • 1
    Anything can be a symbol. If it's not valid by itself, just wrap it in quotes and prepend a colon: `{ :'0' => 'this is a symbol', :'so-is-this' => true }` – Scott Schupbach May 29 '18 at 17:02
16

I don't know why I didn't post this in the first place. The "correct" way to write your tag, <body data-spy="abcd">, in HAML, is to skip the {} entirely and use ():

%body(data-spy="abcd")

If you're not evaluating the values of the attributes as Ruby, you shouldn't be using {:key => value} syntax at all. Stick to (key="value") for static HTML attributes.


Original answer:

HAML has a specific syntax for working with data attributes which CrazyVipa's answer summarizes nicely.

For the sake of completeness, I'll point out that you can also use quoted symbol syntax, both here and anywhere else in Ruby that you want to use a hyphen in a symbol:

%body{ :"data-spy" => "abcd" }

In general, :"text" is equivalent to "text".to_sym, allowing your symbol to contain characters it normally couldn't due to parser limitations. The following are all valid symbols:

:"symbol with spaces"
:"symbol-with-hyphens"
:"symbol
with
newlines"
:"def my_func(); puts 'ok'; end"

Note that quoted symbols will not work with Ruby 1.9's new hash syntax:

{ :"key-1" => "value" } # works in 1.8/1.9
{ "key-1": "value" }  # syntax error
Community
  • 1
  • 1
user229044
  • 232,980
  • 40
  • 330
  • 338
13

For HAML ruby compiler:

%div{data: {some_hyphenated_id: 'value'}}

and HAML automatically converts underscores to hyphens so I get:

<div data-some-hyphenated-id="value"></div>

FYI: if you need empty attribute just use true instead of 'value'

Example:

Haml:

%div{data: {topbar: true}}
%div{data: {image_carousel: true}}

HTML:

<div data-topbar></div>
<div data-image-carousel></div>

To be more specific this syntax is valid for ruby haml gem as well as grunt task grunt-haml with language set to ruby (requires mentioned ruby haml gem installed)

Community
  • 1
  • 1
jmarceli
  • 19,102
  • 6
  • 69
  • 67