Skip to content

Kirby 3.5.7.1

Switching languages in the frontend

With multiple available languages, you probably want to provide a way for your users to switch between those languages.

With the $kirby->languages() method we can fetch all information about available languages. Here are two possible ways to implement such a language switch.

Switch A

The first option is to redirect users to the home page when they select another language. This can be done by using $language->url() for the link.

<nav class="languages">
  <ul>
    <?php foreach($kirby->languages() as $language): ?>
    <li<?php e($kirby->language() == $language, ' class="active"') ?>>
      <a href="<?php echo $language->url() ?>" hreflang="<?php echo $language->code() ?>">
        <?php echo html($language->name()) ?>
      </a>
    </li>
    <?php endforeach ?>
  </ul>
</nav>

Switch B

The second option is to redirect users to the same page in the selected language. This can be done by using $page->url($language->code()) for the link.

<nav class="languages">
  <ul>
    <?php foreach($kirby->languages() as $language): ?>
    <li<?php e($kirby->language() == $language, ' class="active"') ?>>
      <a href="<?= $page->url($language->code()) ?>" hreflang="<?php echo $language->code() ?>">
        <?= html($language->name()) ?>
      </a>
    </li>
    <?php endforeach ?>
  </ul>
</nav>

Switch C

You can use this third option if you want to redirect the user to the error page or any other page you define, e.g. home or search, in case there is no content available in the target language:

<nav class="languages">
  <ul>
  <?php foreach($kirby->languages() as $language): ?>
    <li<?php e($kirby->language() === $language, ' class="active"') ?>>
      <a href="<?php e($page->translation($language->code())->exists(), $page->url($language->code()), page('error')->url($language->code())) ?>"><?php echo $language->code(); ?></a>
    </li>
  <?php endforeach ?>
  </ul>
</nav>