这就是我最终要做的,暂时。我按照hanami 文档定义了一个自定义助手,并使其可用于我的所有视图,如下所示:
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_path
和current_page?(path)
助手,并用它们做我需要做的事情。我不知道这是否是最直接的方法,但至少它有效。