Working with data attributes use Rails tag helpers


#1

How can I convert <div data-controller="slideshow" data-slideshow-index="1"> to the rails 5 tag heplers like <%= tag.div data: { controller: ''slideshow', ...} %> ?


#2

<%= content_tag, :div, data: { controller: 'slideshow', slidesshow_index: 1 }%>


#3

You can also keep the data part with the identifier, if you want.

<%= content_tag :div, "data-controller": "slideshow", "data-slideshow-index": "1" >

#4

I find it’s much easier to keep things straight if I consistently use the quoted key format instead of the explicit data hash format. This is especially true when my controller names span to multiple words.

Because the controller name can appear as both a key prefix AND as a value, I want to be able to use the exact same sequence of characters when I’m typing new code or searching existing code. However, because the explicit hash format requires me to underscore the keys instead of hyphenating them, I can’t do that - I have to keep track of both the underscore and the hyphen forms.

Luckily, the quoted key format keeps everything using hyphens.

Bad:

<%= content_tag(:div, data: {
  controller: 'multi-word-controller',                 # hyphens
  multi_word_controller_datumName: 'datumValue'        # underscores
}) do %>
  <%= content_tag(:div, 'act on me', data: {
    target: 'multi-word-controller.targetName'
  }) %>

  <%= content_tag(:div, 'click me', data: {
    action: 'multi_word_controller#actionName'
  }) %>
<% end %>

Here, I’m consistently using the explicit data-hash format. But for my multi-word controller, I still have to search for both the hyphen (‘multi-word-controller’) and the underscore (‘multi_word_controller’) forms. As I create new DOM nodes, I also have to remember which separator character to use when.

Good:

<%= content_tag(:div,
  'data-controller': 'multi-word-controller',                  # hyphens
  'data-multi-word-controller-datumName': 'datumValue'         # hyphens
 ) do %>
  <%= content_tag(:div, 'act on me'
    'data-target': 'multi-word-controller.targetName'
  ) %>

  <%= content_tag(:div,'click on me'
    'data-action': 'multi-word-controller#actionName'
  ) %>
<% end %>

Here, I’m consistently using the quoted-key format. The identifier ‘multi-word-controller’ is now ALWAYS hyphen-delimited whether it occurs within a key or a value. I don’t have to think as I code my ERB, and I don’t have to use regular expressions when grepping.

There are a couple of side bonuses in the Ruby on Rails world:

  • Ruby names are underscore-delimited. If I have Ruby methods with similar names to my JavaScript objects, I know that when I search for the underscore form of an identifier, I’ll find Ruby code. When I search for the hyphen form, I’ll find JavaScript/DOM code.

  • TextMate theme does a better job of visually distinguishing the quoted keys than it does the explicit hash form.