The given example only creates valid results in case of existing content (text files) at the target destination.
foreach($site->languages() as $language):
$site->page()->url($language->code());
If there are no text files in other languages available, kirby will create “invalid” URLs by just adding a language slug (e.g. “en”) to the original URL. This leads to further problems when using functions like filemtime() on non-existing files.
For this reason, I would need to know how to check the returned absolute string with kirby’s API to send the user to another page in his/her language.
Wouldn’t it be more convenient, if kirby returned a page-like object or null instead of a string?
What do you mean by invalid? Does it produce an error message?
Kirby’s default behavior is to show the content of the default text file if the text file of the non-default language is missing or the fields are empty.
You can prevent this behavior if you filter your pages by language (using a custom filter); you could also check if the content file exists for a language and not show the language switcher in this case or redirect to another page.
But as there is no blogarticle.de.txt, visiting the “invalid” location results in kirby offering the same English content but changing return attributes like
$page->textfile()
to a non existing location.
My goal is to check, if there is a translation available in other languages. If so, provide the link (this already works). If not, link to front page, or even better, link to a search page of the language with a suitable message.
Right now, I have the following code:
<?php foreach($site->languages() as $language):
// get page URL string in other language
$pageTranslation = $site->page()->url($language->code());
// how to check for valid url?
// Created a boolean function isValidTranslationURL below, but I do not know how to check the string with kirby's API
?>
<li <?php e($language->code() == site()->language()->code(),'class="link-active"') ?> >
<a href="<?php echo (isValidTranslationURL($pageTranslation) ? $pageTranslation : $language->url()) ?>" title="<?php echo $language->name()?>">
<img src="/assets/images/<?php echo $language->code ?>.png" width="16" height="11" alt="<?php echo Helpers::getCountryByLanguageCode($language->code()) ?>"></img>
<?php echo html($language->name()) ?>
</a>
</li>
<?php endforeach ?>
You can use the uncommented lines to only display the switch if the content in that language exists. Then you would not need the if-statement within the link tag.
is hard to comprehend when learning a new API. I did not find any information in the documentation on what can be done with a returned content element.
Now I have learned something new. Thank you!
My language switcher is part of a global navigation menu. There should be a switch to change languages at all times, even if there is no translation of the page available. For this reason, I will stick with your error page version.