Hotwire & Turbo in Rails Complete Guide

Hotwire and Turbo in Rails: Complete Guide

Hotwire (HTML Over The Wire) and Turbo are modern tools that simplify building dynamic, fast, and responsive web applications without writing much JavaScript. In this guide, we’ll explore how to implement Hotwire and Turbo in a Application Rails, complete with coding examples.

What is Hotwire and Turbo?

  • Hotwire: A framework for building modern web applications by sending HTML over the wire instead of JSON. It includes Turbo, Stimulus, and Strada.
  • Turbo: A core part of Hotwire that accelerates page navigation and form submissions by avoiding full-page reloads.

Setting Up Hotwire in Rails

Step 1: Add Hotwire to Your Rails App

Add the Hotwire gems to your Gemfile:

gem 'hotwire-rails'

Run the following commands to install Hotwire:
installation groupée

rails hotwire:install

This will install Turbo and Stimulus in your application.

Step 2: Enable Turbo Drive

Turbo Drive is enabled by default and speeds up page navigation by intercepting link clicks and form submissions. No additional setup is required.

Turbo Frames: Building Dynamic Components

Turbo Frames allow you to update specific parts of a page without reloading the entire page.

Example: Updating a Comment Section

  • Create a Turbo Frame
    Wrap the comment section in a Turbo Frame:
    <%= turbo_frame_tag "comments" do %>
    <%= render @post.comments %>
    <% fin %>
  • Add a Form Inside the Frame
    Include a form to add new comments:
    <%= turbo_frame_tag "new_comment" do %>
    <%= form_with model: [@post, Comment.new], data: { turbo_frame: "comments" } do |form| %>
    <%= form.text_area :content %>
    <%= form.submit "Post Comment" %>
    <% fin %>
    <% fin %>
  • Controller Action
    In your CommentsController, render the Turbo Frame after creating a comment:
    créer par défaut
    @comment = @post.comments.create(comment_params)
    répondre_à faire |format|
    format.turbo_stream
    format.html { redirect_to @post }
    fin
    fin
  • Turbo Stream Response
    Create a create.turbo_stream.erb file to update the comments section:
    <%= turbo_stream.append "comments" do %>
    <%= render @comment %>
    <% fin %>

    <%= turbo_stream.replace "new_comment" do %>
    <%= render "form", post: @post, comment: Comment.new %>
    <% fin %>
  • Turbo Streams: Real-Time Updates
    Turbo Streams deliver real-time updates by sending HTML snippets over WebSockets or HTTP.

Example: Broadcasting New Comments

  • Set Up ActionCable
    Ensure ActionCable is enabled in your Rails app.
  • Broadcast New Comments
    In your Comment model, broadcast new comments after creation:
    Commentaire de classe <ApplicationRecord
    after_create_commit :broadcast_comment

    privé

    def broadcast_comment
    broadcast_append_to "post_#{post_id}_comments", partial: "comments/comment", locals: { comment: self }
    fin
    fin
  • Subscribe to Updates
    In your view, subscribe to the Turbo Stream:
    <%= turbo_stream_from "post_#{@post.id}_comments" %>
  • Stimulus: Adding Interactivity
    Stimulus is a lightweight JavaScript framework for adding behavior to HTML.

Example: Toggle Visibility

  • Create a Stimulus Controller
    Generate a Stimulus controller:
    rails generate stimulus toggle
  • Add the Controller Logic
    In app/javascript/controllers/toggle_controller.js:
    import { Controller } from "@hotwired/stimulus"
    export default class extends Controller {
    static targets = ["content"]
    toggle() {
    this.contentTarget.classList.toggle("hidden")
    }
    }
  • Use the Controller in Your View
    Add the controller to your HTML:
    <div data-controller="toggle">
    <button data-action="click->toggle#toggle">Toggle Content</button>
    <div data-toggle-target="content" class="hidden">
    This content is toggled!
    </div>
    </div>

Conclusion

Hotwire and Turbo make it easy to build modern, dynamic Rails applications with minimal JavaScript. By leveraging Turbo Frames, Turbo Streams, and Stimulus, you can create fast, responsive, and interactive user experiences. If you’re looking for expert guidance on implementing these technologies, Railscarma offers top-notch Services de développement de rails to help you build scalable and efficient applications. With Railscarma’s expertise, you can take your Rails projects to the next level while focusing on delivering exceptional user experiences.

Articles Similaires

À propos de l'auteur du message

Laissez un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *


fr_FRFrench