HTML lang tag for not fully translated multi language sites

I’m building a personal website which will be mainly english content/blogposts, but I might add some pages in my native language as well (Dutch). I wanted to have the HTML lang tag to accurately reflect the language of the content, and came up with this:

<?php if($page->translation()->exists()): ?>
<html lang="<?= kirby()->currentlanguage()->code() ?>">
<?php else: ?>
<html lang="<?= kirby()->defaultLanguage()->code() ?>">
<?php endif ?>

This way the language tag is set to dutch (nl) when a translation is available, and otherwise it shows “en”, as that’s the default language of the site, to which Kirby also defaults to when no translation is available.

I was wondering whether this solution is deemed a “correct” one, or whether there is an easier/better way to achieve this. I had not seen a solution implemented for a modern Kirby version and wanted to share my solution for the next person to come across this (albeit small) problem.

That’s very interesting — thanks for sharing. To be honest, I never thought about the fallback language’s lang tag. But it makes sense.

One edge case to consider: if you have partially translated content (e.g., menu in Dutch but text in English), you might want to be more granular with your language tags. You could use the lang attribute on specific elements instead.

That is a good point, I might update this post if I work this out in further detail. As I am currently checking for a translation for the entire page, but I’m not sure whether I can do the same for specific content.