Home > Software engineering >  check current route yii2
check current route yii2

Time:10-17

I just started migrating from laravel to yii2

In Laravel, I had a moment when I checked the current route, and if we are on this page, then we leave only the text, and if not, then we make this text a link

@if(Route::currentRouteName() === 'contact')
  <span >contact</span>
@else
  <a href="{{ route('contact') }}" >contact</a>
@endif

Now I want to do exactly the same on yii2

With a regular link, everything is clear

<a href="<?= Url::to(['/contact']) ?>" >contact</a>

But how can you check the current page?

My controller

public function actionIndex()
    {
        return $this->render('contact');
    }

CodePudding user response:

Assuming the action in your controller is named contact, you could do the following:

{% if $this->context->action->id == "contact" %}
    <span >contact</span>
{% else %}
    <a href="<?= Url::to(['/contact']) ?>" >contact</a>
{% endif %}

CodePudding user response:

You can call getUniqueId() on currently active action:

if (Yii::$app->controller->action->getUniqueId() === 'controller/contact') {

or use $id property if you want "relative" ID of current action:

if (Yii::$app->controller->action->id === 'contact') {

CodePudding user response:

If you have at least yii2 v2.0.3 you can use the following:

echo Url::current();

For more details, https://www.yiiframework.com/doc/guide/2.0/en/helper-url#creating-urls

  • Related