Hanami:从视图或模板访问当前页面的URL

时间:2019-05-01 10:23:27

标签: ruby hanami hanami-router

那段时间,我发现了Hanami(Hanami 1.3),正在完善自己从事的测试项目,找不到从视图中访问当前页面网址/路径的方法。或模板(您可能已经猜到了这个想法是在处理导航链接的可视状态)。

我尝试猜测助手名称(routes.current_pageroutes.current_urlroutes.current ...),但我并不幸运。我检查了routing helpers documentation,浏览了hanami/hanamihanami/router信息库,但没有找到我想要的东西。

我错过了什么吗?或者这根本不是内置的吗?

1 个答案:

答案 0 :(得分:4)

这是我目前要做的事情。我遵循hanami documentation定义了一个自定义帮助程序,并将其提供给我的所有视图,如下所示:

1。创建一个Web::Helpers::PathHelper模块

我可以在其中访问参数并请求路径:

# 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。确保助手目录已由应用程序加载

helpers路径添加到应用程序load_paths变量中,以便在应用程序加载代码时加载我的助手。

  # 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。确保我的新助手可用于每个视图

..通过使用view.prepare中的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。现在,我可以在每个视图中使用我的助手了!

现在,从我的模板或视图对象中,我可以访问自己的current_pathcurrent_page?(path)助手,并对它们进行所需的处理。我不知道这是否是最直接的方法,但至少可以正常工作。