Skip to content

How To: Add Custom Helpers

Tim Moser edited this page Jan 12, 2021 · 3 revisions

Create a new helper file like app/helpers/custom_trestle_helper.rb and put some helper methods in there. In the following example, I am adding a helper that wraps content in a bootstrap panel.

module CustomTrestleHelper
  def custom_helper(options)
    options = options.reverse_merge({
      state: 'default',
      heading: nil,
      footer: nil
    })
    content_tag(:div, class: "panel panel-#{options[:state]}") do
      concat(content_tag(:div, class: "panel-heading") { options[:heading] }) if options[:heading]
      concat(content_tag(:div, class: "panel-body") { yield })
      concat(content_tag(:div, class: "panel-footer") { options[:footer] }) if options[:footer]
    end
  end
end

Make trestle aware of it by updating your config/initializers/trestle.rb:

Trestle.configure do |config|
  # ...
  config.helper CustomTrestleHelper
end

Restart your server.

You can now access those helper methods inside your trestle admin files. For example, in app/admin/launch_codes_admin.rb:

Trestle.resource(:launch_codes) do
  # ...

  form do |launch_code|
    concat(custom_helper({state: 'danger',heading: 'Top Secret'}) do
      text_field :code
      text_field :code_confirmation
    end)
  end
end