在Middleman中如何让link_to生成包含http_prefix的统一根路径链接?
在Middleman中统一生成带http_prefix的根路径链接
针对你遇到的link_to链接不一致问题,有几种实用的解决方法:
使用内置的
root_path辅助方法
Middleman自带的root_path会自动关联你配置的http_prefix,不管当前页面处于哪个层级,都能生成基于网站根路径(包含http_prefix)的链接。用法如下:<%= link_to('Privacy Policy', root_path('privacy-policy')) %>这样无论在根页面还是子页面,都会生成正确的
foo.example.com/my-site/privacy-policy。自定义辅助方法拼接路径
如果需要更灵活的控制,可以在config.rb中定义一个自定义辅助方法,手动拼接http_prefix和目标路径:helpers do def site_root_link(path) File.join(config[:http_prefix], path) end end然后在模板中调用:
<%= link_to('Privacy Policy', site_root_link('privacy-policy')) %>使用
absolute_url生成完整绝对链接
先在config.rb中配置网站根域名:set :url_root, 'http://foo.example.com'之后使用
absolute_url辅助方法生成完整的带http_prefix的绝对链接:<%= link_to('Privacy Policy', absolute_url('privacy-policy')) %>这种方法会直接输出完整的
http://foo.example.com/my-site/privacy-policy,适合需要绝对URL的场景。
内容的提问来源于stack exchange,提问作者Grant Birchmeier
相关产品推荐
相关产品推荐

