Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add HTML5 data- attributes to a rails form label tag?

I have a rails form that has this code:

<%= form_tag("../vehicles", method: "get") do %>
  <div>
    <div>
      <%= label_tag(:address, t("ui.reservations.pickup"), data-addr: 'here') %>
    </div>
    <div>
      <%= label_tag(:address, t("ui.reservations.between_now_and_param", param: @start_date.strftime(    time_format))) %>
    </div>
    <div>

I want to add a HTML data attribute to the first label, so I tried:

<%= label_tag(:address, t("ui.reservations.pickup"), data-addr: 'here') %>

but I get a syntax error:

SyntaxError in Reservations#new

.../_form.html.erb:8: syntax error, unexpected tLABEL

');@output_buffer.append= ( label_tag(:address, t("ui.reservations.pickup"), data-addr: 'here') );@output_buffer.safe_concat('...

I can add it as

    <%= label_tag(:address, t("ui.reservations.pickup"), data: 'here') %>

That generates:

<label for="address" data="here">

but I don't seem to be able to add data-something attributes. I get syntax error.

How can I do this?

like image 326
Michael Durrant Avatar asked Dec 27 '13 15:12

Michael Durrant


People also ask

What is data attribute in html5?

The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

What is Form_for in Ruby?

This is the name used to generate the input's name (and the params' names), example: = form_for Admin.new, as: :user do |f| #^^^^ = f.input :username # will generate an input like this: <input type='text' name='user[username]' #... /> #

What is form tag in Ruby on Rails?

The form_tag Rails helper generates a form withe the POST method by default, and it automatically renders the HTML that we were writing by hand before. Note: We can explicitly specify what HTTP verb to use for the form_tag if we want something other than POST .


1 Answers

The answer provided by @vee will render this correctly. The reason you are getting a syntax error is because data-addr: 'here' is not valid ruby code. That is, you can't have use the JSON hash notation with a key containing a hyphen character. You can modify it to work properly like this:

<%= label_tag(:address, t('ui.reservations.pickup'), 'data-addr' => 'here' %>

But the recommended approach is to declare a nested hash for 'data' attributes:

<%= label_tag(:address, t('ui.reservations.pickup'), :data => {:addr => 'here'} %>

Or simply (as @vee suggested):

<%= label_tag(:address, t('ui.reservations.pickup'), data: {addr: 'here'} %>

[OP edit:] I also found that underscores generate dashes! For example:

<%= label_tag(:address, t('ui.reservations.pickup'), data: {from_base: 'here'} %>

generates

<label for="address" data-from-base="here">
    pickup:
</label>
like image 185
PinnyM Avatar answered Sep 29 '22 02:09

PinnyM