这就是我暂时要做的事情。我按照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 目录
将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。确保我的新助手可用于每个视图
..通过使用application.rb 中的view.prepare 块:
# 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_path 和 current_page?(path) 助手,并使用它们做我需要做的事情。我不知道这是否是最直接的方法,但至少它有效。