Rails:Template with hooks
Appearance
Problem
With an auto-generated Rails template, it would be nice if the template could provide hooks in which custom template code could be added.
Environment:
- Rails 8
Workaround: render_hook method
Bij explicitly calling controller.render_hook partial: 'show_buttons' in the template, you can manually specify in the controller render_before and render_after methods if there should be looked for a show_buttons_before and/or a show_buttons_after partial respectively.
# app/controllers/book_controller.rb
class BookController < ApplicationController
def render_hook(partial:, **options)
(render_before(partial:, **options) +
render_to_string(partial: partial, **options) +
render_after(partial:, **options)
).html_safe
# return unless options && options[:partial]
#
# after_render(partial:, **options)
end
# Provide specified partials with render-before partial
def render_before(partial:, **options)
if %w[show_buttons].include?(partial)
# show_buttons_before
render_to_string(partial: "#{partial}_before", **options)
else
''
end
end
# Provide specified partials with render-after partial
def render_after(partial:, **options)
if %w[show_buttons].include?(partial)
# show_buttons_after
render_to_string(partial: "#{partial}_after", **options)
else
''
end
end
end# app/views/books/show.html.erb
<%= controller.render_hook partial: 'show_buttons' %>