Customizing Blacklight Tutorial Series (v7.11.1)

Helper method overrides

Much of Blacklight is written in a way that is overridable, helper methods are no different.

Let’s take a look at the module that is used to help with some of the layout for Blacklight. This module is mixed into the Blacklight::BlacklightHelperBehavior which allows us to override methods mixed in.

For example, the html_tag_attributes method is used to inject HTML tag attributes into the main Blacklight layout.

  ##
  # Attributes to add to the <html> tag (e.g. lang and dir)
  # @return [Hash]
  def html_tag_attributes
    { lang: I18n.locale }
  end
Default HTML attributes
Default HTML attributes

If we want to modify this method to return something different, we first need to create the CustomLayoutHelper module in our local application.

$ touch app/helpers/custom_layout_helper.rb

And then within custom_layout_helper.rb we need to include the Blacklight::LayoutHelperBehavior mixin.

# app/helpers/custom_layout_helper.rb
module CustomLayoutHelper
  include Blacklight::LayoutHelperBehavior
end

Now we are free to override methods to meet our custom application needs. For example, lets override the html_tag_attributes method.

# app/helpers/custom_layout_helper.rb
module CustomLayoutHelper
  include Blacklight::LayoutHelperBehavior
  
  ##
  # Overriden to include dir
  def html_tag_attributes
    super.merge(dir: 'rtl')
  end
end

This overridden method adds an additional attribute dir="rtl" to display our page right-to-left. While this is not a fully sufficient solution to implementing right-to-left behavior in your site, it does demonstrate how this helper can be extended.

Custom HTML attributes
Custom HTML attributes

This is just one way that the Blacklight code can be overridden and customized. Similar patterns can be used to customize controllers and search behavior.

For more information about overriding helpers, checkout the Blacklight Wiki.