>假设路由是这样的:
Route::get('messages/{messages}', ['as' => 'messages.show', 'uses' => 'MessagesController@show']);
因此,当我们使用 Laravel 的 URL 助手创建 URL 时,
{{ route('messages.show', 12) }}
将显示example.com/messages/12
。
这是正确的。让我们在 URL 中有一些哈希值。
{{ route('messages.show', [12, '#reply_23']) }}
这将显示example.com/messages/12#reply_23
。
这看起来不错。现在,让我们添加一些查询字符串而不是哈希。
{{ route('messages.show', [12, 'ref=email']) }}
这将显示example.com/messages/12?ref=email
。这看起来很酷。
现在添加查询字符串和哈希。
{{ route('messages.show', [12, 'ref=email', '#reply_23']) }}
现在,这将显示example.com/messages/12?ref=email&#reply_23
。由于 URL 中的&
,这看起来有点难看。但是它不会造成很多问题,我想得到一个像example.com/messages/12?ref=email#reply_23
这样的干净 URL。有没有办法摆脱URL中不必要的&
?
编辑:有一个解决方法,但我正在寻找一个可靠的答案。
<a href="{{ route('messages.show', [12, 'ref=email']) }}#reply_23">Link to view on website</a>
Laravel UrlGenerator
类不支持指定 URL 的#fragment
部分。负责构建 URL 的代码如下,您可以看到它只是附加查询字符串参数,没有其他内容:
$uri = strtr(rawurlencode($this->trimUrl(
$root = $this->replaceRoot($route, $domain, $parameters),
$this->replaceRouteParameters($route->uri(), $parameters)
)), $this->dontEncode).$this->getRouteQueryString($parameters);
对代码的快速测试显示,您发布的第二个示例:
{{ route('messages.show', [12, '#reply_23']) }}
实际生成:
/messages/12?#reply_23 // notice the "?" before "#reply_23"
因此,它将#reply_23
视为参数而不是片段。
此缺点的替代方法是编写一个自定义帮助程序函数,该函数允许将片段作为第三个参数传递。您可以使用自定义函数创建文件app/helpers.php
:
function route_with_fragment($name, $parameters = array(), $fragment = '', $absolute = true, $route = null)
{
return route($name, $parameters, $absolute, $route) . $fragment;
}
然后在app/start/global.php
文件的末尾添加以下行:
require app_path().'/helpers.php';
然后,您可以像这样使用它:
{{ route_with_fragment('messages.show', [12, 'ref=email'], '#reply_23') }}
当然,你可以随心所欲地命名函数,如果你觉得我给它的名字太长了。