button_to in Ruby on Rails with custom html_options (here alpine.js x-show)

Viewed 11

For some cases, Ruby on Rails needs a button_to to enable some actions like user logout (devise). My frontend uses Tailwind with alpine.js, latter one using inline attributes like x-show. Unfortunately, I cannot make button_to to output x-show. I'm aware, that button_to can output any kind of data-attributes. For attributes like here - starting with "x" - it does not work.

How is the proper method to get sth. like:

<a x-show="isMobile" class="block rounded-md px-3 py-2 text-base font-medium text-gray-400 hover:bg-gray-700 hover:text-white" role="menuitem" tabindex="-1" href="/users/edit">Edit profile</a>

?

My Rails code looks like this now:

<%= link_to "Edit profile", edit_user_registration_path, x:{show: "isMobile"}, class:"block rounded-md px-3 py-2 text-base font-medium text-gray-400 hover:bg-gray-700 hover:text-white", role:"menuitem", tabindex:"-1" %>

which outputs

<a x="show isMobile" class="block rounded-md px-3 py-2 text-base font-medium text-gray-400 hover:bg-gray-700 hover:text-white" role="menuitem" tabindex="-1" href="/users/edit">Edit profile</a>

what is obviously not correct and will not work for alpine.js

Thanks in advance!

1 Answers

A friend helped me with it. The solution is something like:

<%= button_to "Sign in", new_user_session_path, class: "btn btn--dark", "x-show": "isMobile" %>

So you need to write it in this shape: "x-show": "isMobile"

Related