DEV Community

Tyler Smith
Tyler Smith

Posted on • Edited on

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)