Rails url helpers as liquid filters

14 May 2019 • Tags: rails — liquid — filters

For a new personal project, Checklistenguru.de I wanted to use liquid for the longish description texts that get filled with links to other pages inside the app. Naturally the usual url helpers get used and I had to come up with a way to use them.

I got the inspiration from Philippe Bourgau and the following lines will allow you to use any named route _path in a liquid filter, e.g. {{"moon-trip" | public_template_list_path }}. If you also set the default_url_options you will be able to use the _url helpers as well.

# app/helpers/link_helper.rb
# yes, not in the initializers but the helpers

module LinkFilter
  include Rails.application.routes.url_helpers
  def default_url_options
    {}
  end
end

Liquid::Template.register_filter(LinkFilter)