skip to Main Content

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 class="contact-link active">contact</span>
@else
  <a href="{{ route('contact') }}" class="contact-link">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']) ?>" class="contact-link">contact</a>

But how can you check the current page?

My controller

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

3

Answers


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

    {% if $this->context->action->id == "contact" %}
        <span class="contact-link active">contact</span>
    {% else %}
        <a href="<?= Url::to(['/contact']) ?>" class="contact-link">contact</a>
    {% endif %}
    
    Login or Signup to reply.
  2. 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') {
    
    Login or Signup to reply.
  3. get current controller name:

    Yii::$app->controller->id;
    

    current action name:

    Yii::$app->controller->action->id;
    

    current route:

    Yii::$app->requestedRoute
    

    This code can help you. Or you can modify your code based on current route.

    <?php
    if (Yii::$app->controller->id === 'mycontroller' && Yii::$app->controller->action->id == 'index') {
        ?>
        <span class="contact-link active">contact</span>
        <?php
    } else {
        ?>
        <a href="<?= Url::to(['/contact']) ?>" class="contact-link">contact</a>
        <?php
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search