Laravel 5.1-获取当前路线 [英] Laravel 5.1 - get current route
问题描述
我正在开发一个为每个视图自动获取资产(.css,.js)的函数.因此,它可以正常工作,例如," http://mywebsite.com/displayitems ",/home,/关于等等.
I'm working on a function to get assets (.css, .js) automatically for each view. So it works fine for let's say, "http://mywebsite.com/displayitems", /home, /about etc.
但是因为我使用$_SERVER['REQUEST_URI']
编写了函数,所以当我使用/displayitems/1
之类的路由时,由于路由中的"/1",我想到了一个问题.
But since I wrote the function using $_SERVER['REQUEST_URI']
, I came up with an issue when I had a route like /displayitems/1
because of the "/1" in the route.
当时在Laravel 4.x中,我有一个很棒的方法,但可惜的是,它在Laravel 5.4中无法以同样的方式工作.
Back then in Laravel 4.x I had a great way to do it but sadly it doesn't work the same way in Laravel 5.4.
我一直在互联网上寻找一种获得当前路线的好方法,但是没有成功.事实是,我必须忽略请求URL中的任何参数.
I've been searching through the internet for a good method to get the current route but no success. The thing is that I have to ignore any parameters in the request URL.
如果有人有线索,或者我做错了,还有完全不同的更好的方法吗?
If anyone has a clue, or maybe am I doing it wrong and there's a completely different, better way to do it?
P.S我当前的功能:
P.S My current function:
public static function getAllRouteAssets() {
$route = $_SERVER['REQUEST_URI'];
if($route == "/") {
$tag = '<link href="' . asset("assets/css/pages/home.css") . '" rel="stylesheet" type="text/css"/>';
}
else {
// CSS
$tag = '<link href="' . asset("assets/css/pages" . $route . ".css") . '" rel="stylesheet" type="text/css"/>';
}
echo $tag;
//TODO: Check if file exists, homepage condition, js...
}
推荐答案
您可以尝试以下方法:
// Add the following (`use Illuminate\Http\Request`) statement at top your the class
public static function getAllRouteAssets(Request $request)
{
// Get the current route
$currentRoute = $request->route();
}
更新(从IoC/服务容器获取Request实例,并调用route()
以获得当前路由):
Update (Get the Request instance from IoC/Service container and call route()
to get current route):
app('request')->route(); // Current route has been retrieved
如果要将当前路由作为参数传递给getAllRouteAssets
方法,则必须更改typehint
或传递Request
并从getAllRouteAssets
方法中调用route
方法.
If you want to pass the current route as a parameter to your getAllRouteAssets
method then you have to change the typehint
or pass the Request
and call the route
method from within the getAllRouteAssets
method.
这篇关于Laravel 5.1-获取当前路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!