Blog overview

CraftCMS: Smarter Translation Files

On my last Craft CMS client project at work, I was a bit pissed about our translation file. Long story short: It's messy! We have a lot of static translations in this project, and it's a bit hard to manage them in one big file. So, our first approach was to use generic strings to translate rather than the thing to be translated itself. That looked like this:

This helped us have more explicit strings and context in our translation file. All our strings start with: translate, so it's easy to search against all templates for translations. Great advantage! But it does not solve the problem that you can have a massive file at the end. Yes, working with a file like that is possible, but we don't like it.

A much better approach

We thought about how we could optimize here. It's pretty simple. Place your files where they belong. That means we say goodbye to one large and messy file and say hello to component/page-based translations. Let me explain with a small example. Our folder structure looks like this:

In our components folder, we find all our components. Each component can have a different set of files. If we have a template file (twig in our case) and need static translations, we also place a PHP file for each language in that folder. Our naming for this file is:

TRANSLATE.LANG.CONTEXT.COMPONENT.php
translate.en.component.code.php

Let's look at a complete example

We have two sites (German and English), and we have a code component in our example. That means we need two translation files.

templates/_components/code/translate.de.component.code.php
templates/_components/code/translate.en.component.code.php

In our main translation file, we have to include this component translation file and we have to merge it all. In this example, we import our code file and two other components. We also have a global array where we can place global translations like weekdays or stuff like that. In the end, it looks like this:

translations/de/site.php
translations/en/site.php

What do you think? Let me know!