Yii 检查主页

2022-01-04 00:00:00 php yii yii-url-manager

Yii 中是否有内置方法或属性来检查页面是否为主页?

我知道我可以使用这样的东西:

$controller = Yii::app()->getController();$isHome = $controller->getAction()->getId() === 'index' ?真假;

或者把它放在主控制器的一个方法中,但我正在寻找更干净的东西.

谢谢.

解决方案

如果要查看当前页面,即 action 是当前控制器的默认..

$controller = Yii::app()->getController();$isHome = $controller->action->id === $controller->defaultAction->id ?真假;

<块引用>

dafeultaction 可能并不总是'index',它可以改变,所以你需要将它与 defaultAction 进行比较..

如果你的意思是网站的默认页面,那么你需要将你的控制器与 defaultController.. 进行比较.

$controller = Yii::app()->getController();$default_controller = Yii::app()->defaultController;$isHome = (($controller->id === $default_controller->id) && ($controller->action->id === $controller->defaultAction->id)) ?真假;

在 Yii2 中:

$controller = Yii::$app->controller;$default_controller = Yii::$app->defaultRoute;$isHome = (($controller->id === $default_controller) && ($controller->action->id === $controller->defaultAction)) ?真假;

Is there a buildin method or property in Yii to check if page is homepage?

I know i can use something like this:

$controller = Yii::app()->getController();
$isHome = $controller->getAction()->getId() === 'index' ? true : false;

Or put it in a method in main controller, but i am looking for something cleaner.

Thanks.

解决方案

If You want to check the current page, ie action is the default of the current controller..

$controller = Yii::app()->getController();
$isHome = $controller->action->id === $controller->defaultAction->id ? true : false;

dafeultaction may not always be 'index', it can be changed, so you need to compare it with defaultAction instead..

And by homepage if you mean the defult page of site, then you need to compare your controller also with defaultController..

$controller = Yii::app()->getController();
$default_controller = Yii::app()->defaultController;
$isHome = (($controller->id === $default_controller->id) && ($controller->action->id === $controller->defaultAction->id)) ? true : false;

In Yii2:

$controller = Yii::$app->controller;
$default_controller = Yii::$app->defaultRoute;
$isHome = (($controller->id === $default_controller) && ($controller->action->id === $controller->defaultAction)) ? true : false;

相关文章