DEV Community

Tyler Smith
Tyler Smith

Posted on • Edited on

4 1

Using Alpine.js directives on form_with in Ruby on Rails

Alpine.js makes Vue-like declarative state-driven UI available in server-rendered templates without the complexity of a typical JS toolchain.

Alpine can be especially useful on HTML forms. Because the default approach to forms in Ruby on Rails uses the framework's form_with function instead of an HTML <form /> tag, it's not immediately clear how to use Alpine's directives in Rails. Thankfully, it's relatively straight forward to use Alpine directives in the form_with function. Take a look at the example below:

<%= form_with(model: blog_post, html: {"x-data": "{}"}) do |form| %>
    <%= form.button "x-on:click": "alert('Hello!')", type: "button" do %>
      click me
    <% end %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

I hope this helps you get up-and-running with Alpine.js when using Rails as your back-end framework. Happy coding!

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more