1

This is the scenario: I need the translations strings in both Twig and JS (For React). Of course I'm covered in the Twig part., and I don't want to maintain two different files (php and json). So I've created a custom module, where I can read the files, like:

public function getTranslations($language, $translationsFileName = 'site')
{
    if (file_exists(CRAFT_BASE_PATH . '/translations/' . $language . '/' . $translationsFileName . '.php')) {
        return require_once(CRAFT_BASE_PATH . '/translations/' . $language . '/' . $translationsFileName . '.php');
    }
}

Usage:

{{ craft.translations.getTranslations(craft.locale) | json_encode | raw }}

It works, but, is this a good way? Is there a default Craft/Yii way?

  • 1
    Would it be an option for you to do it like Craft does it in the CP (I use the same way in my frontend) instead of just serializing the entire array? – Robin Schambach Jul 11 '18 at 19:51
  • Like {{ "var" | translate }} you mean? Sorry, I didn't understand. – Jorge Anzola Jul 12 '18 at 12:16
  • No I mean by using the RegisterTranslation docs.craftcms.com/api/v3/… function in your frontend. You only need to define a Craft object and copy the Craft.t function – Robin Schambach Jul 12 '18 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.