1

Craft CMS doesn't have TWIG filter country_name. Even by default country name filter package is not available in twig. We need to install the corresponding package. https://twig.symfony.com/doc/3.x/filters/country_name.html

How can I install the package and use country_name filter in Craft CMS?

composer require twig/intl-extra installs the package. But still, the filter is not working. Am I missing anything? Is the installation method works with Craft cms?

1 Answer 1

2

You need to register the extension with the Twig environment. First, install the extension with Composer. Then see the code example in the documentation page you linked:

$twig = new \Twig\Environment(...);
$twig->addExtension(new IntlExtension());

This adds the extension to the environment so its filters will be available in your templates. Of course, Craft creates the Twig environment for you, so you need to use hooks to register the extension at the appropriate point in the lifecycle. You can put the following code in a simple site module:

use Twig\Extra\Intl\IntlExtension;

public function init()
{
    parent::init();

    if (Craft::$app->request->getIsSiteRequest()) {
        $extension = new IntlExtension();
        Craft::$app->view->registerTwigExtension($extension);
    }
}

See Register a Twig Extension for details.

3
  • Thanks for the details. Do we need to develop a module/plugin to register the extension to use in craft cms? or, is there a way to proceed without them?
    – Parthiban
    Commented Dec 21, 2021 at 3:31
  • @Parthiban Modules and plugins aren't the same thing. Modules are site-specific components that can contain as little or as much you need them to. Creating a small module to include the hook code above is very simple and only takes a couple of minutes. Check the link above to get started. You can also create a starter module on pluginfactory.io, this will help you get started.
    – MoritzLost
    Commented Dec 21, 2021 at 11:55
  • Sure, I will do a simple module and proceed. Thanks.
    – Parthiban
    Commented Dec 22, 2021 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.