0

I'm using Ruby on Rails 7 with the Turbo Rails gem, which provides the turbo_frame_tag method.

I would like to add default html data attributes to all the <turbo-frame> tags that are generated through turbo_frame_tag. That is, given the default data attribute to add is data-custom="value", I would like to generate the following HTML each time I use turbo_frame_tag:

<turbo-frame id="..." data-custom="value">...</turbo-frame>

How can I make that in an initializer?

Backo
  • 18,291
  • 27
  • 103
  • 170

1 Answers1

0

It can be done like this... first define your custom attributes in an initializer:

# config/initializers/custom_turbo_frame_attributes.rb
CustomTurboFrameAttributes = {foo: 'bar', baz: 'qux'}

Then override the Rails turbo_frame_tag view helper to include your custom attributes. I did this by including the following in app/helpers/application_helper.rb. There's probably a cleaner way, but I didn't take the time to find it!

# app/helpers/application_helper.rb
module Turbo
  module FramesHelper
    def turbo_frame_tag(*ids, src: nil, target: nil, **attributes, &block)
      id = ids.map { |id| id.respond_to?(:to_key) ? ActionView::RecordIdentifier.dom_id(id) : id }.join("_")
      src = url_for(src) if src.present?
      attributes.merge!(CustomTurboFrameAttributes) # bingo! here are your custom attributes
      tag.turbo_frame(**attributes.merge(src: src, target: target).compact, &block)
    end
  end
end

This is just the Turbo view helper copied and changed to include your custom attributes.

An alternative, if you can live with it, is to define a helper called custom_turbo_frame_tag, and add in your attributes (defined as above). This approach then calls the standard ActionView turbo_frame_tag helper, and so it might work better in case future Rails versions change the built-in helper.

# app/helpers/application_helper.rb
module Turbo
  module FramesHelper
    def custom_turbo_frame_tag(*ids, src: nil, target: nil, **attributes, &block)
      attributes.merge!(CustomTurboFrameAttributes)
      turbo_frame_tag(ids, src: src, target: target, **attributes, &block)
    end
  end
end
Les Nightingill
  • 5,662
  • 1
  • 29
  • 32