Using Alpine.js directives on form_with in Ruby on Rails
Tyler Smith

Tyler Smith @tylerlwsmith

About: I'm a software developer who writes about Laravel, JavaScript, Rails, Linux, Docker, WordPress and the tech industry. Follow me on Twitter @tylerlwsmith

Location:
Sacramento, California
Joined:
Apr 17, 2018

Using Alpine.js directives on form_with in Ruby on Rails

Publish Date: Sep 10 '22
6 0

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!

Comments 0 total

    Add comment