'How to add aria-label attribute to a link in a view?

I'm trying to add the aria-label attribute to a link to make it more accessible. When I'm doing this, it works as expected:

<a href="/" class="site-name <%= is_active('home') %>" aria-label="<%= get_aria_label_current_page('home') %>">Version Postman</a>

But this doesn't:

<%= link_to t('nav.projects'), projects_path, class: is_active('projects'), aria-label: get_aria_label_current_page('home') %>

I get an "unexpected tLABEL" syntax error. Anyone knows what's the problem?

Thanks.



Solution 1:[1]

It's the dash on the label creating the problem. Try this instead:

<%= link_to t('nav.projects'),
            projects_path, class: is_active('projects'),
            'aria-label' => get_aria_label_current_page('home') %>

Update

In ruby 2.2 now you could do:

'aria-label': get_aria_label_current_page('home')

Solution 2:[2]

As of at least Rails 5.2 this works too:

<%= link_to t('nav.projects'),
            projects_path,
            class: is_active('projects'),
            aria: { label: get_aria_label_current_page('home') } %>

This is similar to how data-* attributes work, which is nice since you can add more than one and have them grouped.

This may work on earlier versions but I have not checked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 notapatch
Solution 2 Todd