This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.

gtf21
gtf21

I have a theme I've developed for a client, and we've also developed a plugin for some of the data models. We now need to localise in both English and French. I would like to create a tag for Twig such that I can move from

{% content 'folder/file' %}

to

{% locale 'folder/file' %}

such that either content/en/folder/file.md or content/fr/folder/file.md is loaded depending on which locale is selected.

What I'm not sure about:

  • where should I write the classes to do this (plugin/theme)? It makes sense to do this in the theme because I need to know where the content files are being loaded from.
  • where and how should I register the function for this tag?
  • if I develop this in my plugin, how do I reference files that are in the theme?
daftspunky
daftspunky

This is called a Token Parser, you can register them using the key tokens and the value of a class name. See modules\cms\twig\ContentTokenParser.php for an example of a token parser class. Twig documentation also provides more details on this.

Example registration code:

public function registerMarkupTags()
{
    return [
        'tokens' => [
            // {% mytoken ... %}
            'mytoken' => 'Acme\Demo\Twig\MyTokenParser',
        ]
    ];
}

Last updated

gtf21
gtf21

Thanks @daftspunk, any concrete answers on my other questions?

I've built a token parser and localisation "node" basing them off the ContentTokenParser and ContentNode... Not sure how correct they are but I'll give them a go and see.

gtf21
gtf21

For some reason, despite the plugin being loaded, Twig is not recognising my localise tag, despite it being defined as you outline.

pxpx
pxpx

Most likely got this fixed as it's an old post but if like me someone stumbles upon it, you need to pass an instance.

Top of file:

use Acme\Demo\Twig\MyTokenParser;

Within the registration

public function registerMarkupTags()
{
    return [
        'tokens' => [
            // {% mytoken ... %}
            'mytoken' => new MyTokenParser(),
        ]
    ];
}

The MarkupManager expects an instance to be sent through and not a string, so it would fail everytime with a string.

Last updated

1-5 of 5

You cannot edit posts or make replies: the forum has moved to talk.octobercms.com.