ruby-on-railsrenderpartialhotwire-railsturbostimulus-rails

Rails Turbo How do I render a partial when clicked?


I have a Ruby on Rails application with a popup currently set to show and hide through Turbo Toggle. However, I've noticed that this approach impacts the page loading speed.

To reduce the load times of the parent page I was thinking about rendering the tab only when clicked.

.div{ "data-controller": "toggle" } %div.{"data-action": "click->toggle#toggle touch->toggle#toggle"} = link_to 'Customers' = render "customers"


Solution

  • OK, let's try figure out what could be helpful for you. Basically you have three options

    1. Eager-loading of frames for a better performance
    2. Using Turbo-Frames for navigation
    3. Using Stimulus (as you are already using it)

    Either way, you have to provide a separate method and a view for rendering the customers-part - something like 'customer/:id'

    For the first two options to work you have to make sure, that your customer-layout (the sub-layout) includes the turbo-frames tag. Using Rails you can do:

    <%= turbo_frame_tag(@customer) do %>
      <%= #all of your customer-stuff %>
    <% end %>
    

    which renders into

     <turbo-frame id="customer_1">all of your customer-stuff</turbo-frame>
    

    For the first option, the eager-loading of Frames is done this way:

    <%= turbo_frame_tag @customer, src: customer_path(@customer) %>
    

    For the second, it's just

    <%= turbo_frame_tag @customer %>
    

    Just make sure that you create the turbe-frame tag the same way as in your sublayout, and the replacement should happen automatically.

    For the third option you could fetch the sub-page /customer/:id and replace the div for yourself. Have a look at https://stimulus.hotwired.dev/handbook/working-with-external-resources for a starting example.