3

I'm creating a multilingual site and I'm looking to pass some additional configuration data to Twig so I can use it in my template. For example, suppose I have a configuration like this:

{
  "serviceName":        "arabic",
  "language":           "ar",
  "textDirection":      "rtl",
  "socialMediaButtons": ["twitter", "facebook"],
  ...
}

I'd like to use this data to set the dir attribute in my template:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ craft.locale }}" dir="{{ config.textDirection }}">
<head>
  ...
</head>

Is there an easy way to do this?

My project structure looks like this:

image

Where each locale directory has a config file.

Thanks!

5

The answer is to create a custom plugin that will read the json files from the folders in the public directory, parse the json, and pull them into the template.

An alternative solution is to use Craft custom config files. (Not the answer you're looking for but would work very well.)

In craft/config create a file like localedata.php and make it something like this:

<?php

/**
 * Return an array indexed by locale code
 */
return [
    'ar' => [
        'serviceName' => 'arabic',
        'language' => 'ar',
        'textDirection' => 'rtl',
        'socialMediaButtons' => ['twitter', 'facebook'],
    ],
    'en' => [
        //...
    ],
    // etc
];

Then in your template you could do something like this:

{#
    If the current locale is `ar` (Arabic) then this will set `localeData`
    from the array index "ar" in the config file
#}
{% set localeData = craft.config.get(craft.locale, 'localedata') %}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ craft.locale }}" dir="{{ localeData.textDirection }}">
<head>
  ...
</head>
|improve this answer|||||
1

After a bit more research, I found that there is additional data associated with the locales. This article was of help. I was able to do this:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ craft.locale }}" dir="{{ craft.i18n.getLocaleData().orientation }}">

to set the dir attribute.

For all other configuration data, Sam's answer works well.

|improve this answer|||||

Your Answer

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

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