rubyhanamihanami-router

Hanami : access current page URL from views or templates


I'm discovering Hanami those days (Hanami 1.3), I'm polishing the test project I've worked on, and I can't find a way to access the current page url/path from a view or a template (the idea is handling the navigation links visual state, as you may have guessed).

I've tried to guess helper names (routes.current_page, routes.current_url, routes.current...) but I've not been lucky. I've checked the routing helpers documentation, got through the hanami/hanami and hanami/router repositories but didn't find what I was looking for.

Did I miss something or is this simply not built-in?


Solution

  • Here's what I ended up doing, for the moment. I followed hanami documentation defined a custom helper and made it available to all of my views, like this:

    1. Create a Web::Helpers::PathHelper module

    There I can access the params and request path:

    # apps/web/helpers/path_helper.rb
    module Web
      module Helpers
        module PathHelper
          private
    
          def current_path
            params.env['REQUEST_PATH']
          end
    
          def current_page?(path)
            current_path == path
          end
        end
      end
    end
    

    2. Make sure the helpers directory is loaded by the app

    Added the helpers path to the application load_paths variable, so that my helpers get loaded when the app loads the code.

      # apps/web/application.rb
      # Relative load paths where this application will recursively load the
      # code.
      #
      # When you add new directories, remember to add them here.
      #
      load_paths << [
        'helpers',
        'controllers',
        'views'
      ]
    

    3. Make sure my new helper is available for each view

    ..by using the view.prepare block in application.rb:

      # apps/web/application.rb
      # Configure the code that will yield each time Web::View is included
      # This is useful for sharing common functionality
      #
      # See: http://www.rubydoc.info/gems/hanami-view#Configuration
      view.prepare do
        include Hanami::Helpers
        include Web::Assets::Helpers
        include Web::Helpers::PathHelper
      end
    

    4. And now I can use my helpers in every view!

    And now, from my template or my view objects, I can access my own current_path and current_page?(path) helpers, and do what I need to do with them. I don't know if that's the most straightforward way but at least it's working.