Localization function in Twig with CodeIgniter

CodeIgniter has a beautiful and simple Localization framework with each language in it’s folder and using aliases in views to get the localized version of a specific text. I will not go into details about this as I’m assuming you already have been using it for a while. For more details on it, please visit the Official Documentation

I did mention in a different post that I prefer working with Twig in conjunction with CI and, since the current Twig does not know where to pick-up my localized text from, I will show you how to create a quick and dirty fix.

Adding the Twig Function

Assuming that you’ve already implemented Twig in your BaseController as described in a previous post (Twig Integration with Codeigniter) the quick method for adding a TwigFunction is within the same initController function where you’ve declared you Twig instance:

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
        ...........

        $loader = new \Twig\Loader\FilesystemLoader($appViewPaths);
        $this->twig = new \Twig\Environment($loader, [
            'cache' => WRITEPATH.'/cache/twig',
            'auto_reload'=> true
        ]);

        $this->twig->addFunction(new \Twig\TwigFunction('lang', function ($var, $args=[]){
            $localizedString = lang($var,$args,$this->language);
            return vsprintf($localizedString,$args);
            }));
       
       .............
}

Note that $this->language is the locale. You should take care of it 🙂 before using the function. The good news is that the above function allows you to also pass an array of variables (arguments) to the lang function in order to pre-fill a text.

using the lang function

Let’s say you have a language file in App/Language/en (for English locale) called Home.php

<?php

return [
      'title' => 'Hello %s, nice to see you again!',  // <-this takes one variable passed as argument to the twig lang function
      'subtitle' => 'Welcome to %s, the capital of %s' // <-this takes two variables passed as arguments to the twig lang function
      'text'=> 'Enjoy your stay',
];

In your HTML all you now need to do is:

<html>
           <h1>{{ lang('Home.title',['Stefan']) }}</h1>
           <h3>{{ lang('Home.subtitle',['Bucharest','Romania'] }}</h3>
           <p>{{ lang('Home.text') }}</p>
</html>

and you will get the expected result:

Hello Stefan, nice to see you again!

Welcome to Bucharest, the capital of Romania

Enjoy your stay

Simple and effective!

More functions to come!


Posted

in

,

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *