Easy Multi-Language Twig Apps with Gettext
There are many approaches for adding new languages to your application’s UI. Though some userland solutions like symfony/translation are arguably simpler to use, they’re slower than the good old native gettext by an order of several magnitudes.
In this tutorial, we’ll modify an English-only application to use gettext. Through this, we’ll demonstrate that getting internationalization up and running in an already existing app is not only possible, but relatively easy.
The application in question will be our own nofw – a ready-to-use skeleton app.
Bootstrapping and Basics
We’ll be using our trusty Homestead Improved as always as an environment – if you’d like to follow along, please fire it up. Our box already has gettext installed and activated. We’ll see how to manually install it for deployment purposes at the end of this tutorial.
Since nofw uses Twig, we’ll need the i18n extension. To start the project off right, here’s the full process:
git clone https://github.com/swader/nofw
cd nofw
git checkout tags/2.93 -b 2.93
composer require twig/extensions
Note: the above commands clone an older version of nofw – one without the internationalization features built in – so that readers can follow along with the tutorial.
This will install both Twig’s extensions, and all the project’s dependencies. Follow the procedure from the README to set up the rest of the nofw app (the database end), then return to this post.
The app should be up and running now.
The syntax for getting a translatable string is gettext("string")
or its alias: _("string")
– that is, _()
is the function we call and "string"
is the string we’re translating. If a translation for "string"
isn’t found, then the original (which is considered a placeholder) value is returned. Placeholders are usually full strings in the most popular language for the site’s audience, so that if translation fails for some reason, readable text is still rendered.
Continue reading %Easy Multi-Language Twig Apps with Gettext%
LEAVE A REPLY
You must be logged in to post a comment.