How to do data- attributes with haml and rails?

Michael Durrant picture Michael Durrant · Jun 22, 2014 · Viewed 35.2k times · Source

I can have

%a{href: '#', data_toggle_description_length: 'toggle_me_ajax'}

which it gives me underscores not dashes, i.e.

<a href="#" data_toggle_description_length="toggle_me_ajax"></a>

However I want to have HTML5 data- attributes, i.e.

<a href="#" data-toggle-description-length="toggle_me_ajax"></a>

but when I try replacing underscores with dashes, i.e.

%a{href: '#', data-toggle-description-length: 'toggle_me_ajax'}

I get syntax errors:

/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected tLABEL
...data-toggle-description-length: 'toggle_me_ajax')}>\n    tog...
...                               ^
/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected ')', expecting '}'
...ption-length: 'toggle_me_ajax')}>\n    toggleMeAjax\n  </a>\...
...                               ^
/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unknown regexp options - pa
/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $undefined
... toggleMeAjax\n  </a>\n</span>\n", -1, false);::Haml::Util.h...
...                               ^
/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: unterminated string meets end of file
/home/durrantm/Dropnot/webs/rails_apps/linker/app/views/links/_links.html.haml:13: syntax error, unexpected $end, expecting '}'

Answer

Mandeep picture Mandeep · Jun 22, 2014

Try this:

%a{"data-toggle-description-length" => "toggle_me_ajax", href: "#"}

OR

%a{href: "#", :data => {:toggle_description_length => "toggle_me_ajax"}}

For more details refer here

You can also use html2haml converter available online

EDIT:

As mentioned in comments there are a couple more syntaxes which would work

 %a{href: "#", { "data-toggle-description-length": "toggle_me_ajax" }}

OR

%a{href: "#", { :"data-toggle-description-length" => "toggle_me_ajax" }}

I would still prefer first two though as I think latter ones look ugly and kinda messy.