{"id":13606585,"url":"https://github.com/wintercms/wn-translate-plugin","last_synced_at":"2025-04-05T20:06:12.782Z","repository":{"id":39674120,"uuid":"345011083","full_name":"wintercms/wn-translate-plugin","owner":"wintercms","description":"Translate plugin for Winter CMS","archived":false,"fork":false,"pushed_at":"2025-03-26T07:13:01.000Z","size":742,"stargazers_count":16,"open_issues_count":6,"forks_count":18,"subscribers_count":5,"default_branch":"main","last_synced_at":"2025-04-02T04:49:01.750Z","etag":null,"topics":["hacktoberfest"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wintercms.png","metadata":{"funding":{"github":"wintercms","open_collective":"wintercms"},"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-06T05:11:02.000Z","updated_at":"2025-03-29T18:39:44.000Z","dependencies_parsed_at":"2023-12-19T10:02:13.261Z","dependency_job_id":"1f8048b2-1263-4d37-b91e-37892a7f4c6d","html_url":"https://github.com/wintercms/wn-translate-plugin","commit_stats":{"total_commits":498,"total_committers":103,"mean_commits":4.834951456310679,"dds":0.6586345381526104,"last_synced_commit":"90f6ece698f9e4202637adbb2bdf5b91ee26535c"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wintercms%2Fwn-translate-plugin","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wintercms%2Fwn-translate-plugin/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wintercms%2Fwn-translate-plugin/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wintercms%2Fwn-translate-plugin/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wintercms","download_url":"https://codeload.github.com/wintercms/wn-translate-plugin/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247393568,"owners_count":20931812,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["hacktoberfest"],"created_at":"2024-08-01T19:01:10.452Z","updated_at":"2025-04-05T20:06:12.749Z","avatar_url":"https://github.com/wintercms.png","language":"PHP","funding_links":["https://github.com/sponsors/wintercms","https://opencollective.com/wintercms"],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"readme":"# Translate Plugin\n\nAdds multi-lingual / localization capabilities to the frontends of Winter CMS websites.\n\nSupports:\n- Frontend Language Picker component\n- Static string/message localizations\n- CMS Content files localizations\n- Mail template localizations\n- Model attribute localizations\n- Theme Data \u0026 Settings localizations\n- URL \u0026 URL attribute localizations\n- Simple UX in backend for providing localized values\n- Easy integration with external plugins\n\n## Installation\n\nThis plugin is available for installation via [Composer](http://getcomposer.org/).\n\n```bash\ncomposer require winter/wn-translate-plugin\n```\n\nAfter installing the plugin you will need to run the migrations and (if you are using a [public folder](https://wintercms.com/docs/develop/docs/setup/configuration#using-a-public-folder)) [republish your public directory](https://wintercms.com/docs/develop/docs/console/setup-maintenance#mirror-public-files).\n\n```bash\nphp artisan migrate\n```\n\n## Selecting a language\n\nDifferent languages can be set up in the back-end area, with a single default language selected. This activates the use of the language on the front-end and in the back-end UI.\n\nA visitor can select a language by prefixing the language code to the URL, this is then stored in the user's session as their chosen language. For example:\n\n* `http://website/ru/` will display the site in Russian\n* `http://website/fr/` will display the site in French\n* `http://website/` will display the site in the default language or the user's chosen language.\n\n## Language Picker Component\n\nA visitor can select their chosen language using the `LocalePicker` component. This component will display a simple dropdown that changes the page language depending on the selection.\n\n```twig\ntitle = \"Home\"\nurl = \"/\"\n\n[localePicker]\n==\n\u003ch3\u003e{{ 'Please select your language:'|_ }}\u003c/h3\u003e\n{% component 'localePicker' %}\n```\n\nIf translated, the text above will appear as whatever language is selected by the user. The dropdown is very basic and is intended to be restyled. A simpler example might be:\n\n```twig\n[...]\n==\n\u003cp\u003e\n    Switch language to:\n    \u003ca href=\"javascript:;\" data-request=\"onSwitchLocale\" data-request-data=\"locale: 'en'\"\u003eEnglish\u003c/a\u003e,\n    \u003ca href=\"javascript:;\" data-request=\"onSwitchLocale\" data-request-data=\"locale: 'ru'\"\u003eRussian\u003c/a\u003e\n\u003c/p\u003e\n```\n\n## Message translation\n\nMessage or string translation is the conversion of adhoc strings used throughout the site. A message can be translated with parameters.\n\n```twig\n{{ 'site.name' | _ }}\n\n{{ 'Welcome to our website!' | _ }}\n\n{{ 'Hello :name!' | _({ name: 'Friend' }) }}\n```\n\nA message can also be translated for a choice usage.\n\n```twig\n{{ 'There are no apples|There are :number applies!' | __(2, { number: 'two' }) }}\n```\n\nOr you set a locale manually by passing a second argument.\n\n```twig\n{{ 'this is always english' | _({}, 'en') }}\n```\n\nThemes can provide default values for these messages by defining a `translate` key in the `theme.yaml` file, located in the theme directory.\n\n```yaml\nname: My Theme\n# [...]\n\ntranslate:\n    en:\n        site.name: 'My Website'\n        nav.home: 'Home'\n        nav.video: 'Video'\n        title.home: 'Welcome Home'\n        title.video: 'Screencast Video'\n```\n\nYou may also define the translations in a separate file, where the path is relative to the theme. The following definition will source the default messages from the file **config/lang.yaml** inside the theme.\n\n```yaml\nname: My Theme\n# [...]\n\ntranslate: config/lang.yaml\n```\n\nThis is an example of **config/lang.yaml** file with two languages:\n\n```yaml\nen:\n    site.name: 'My Website'\n    nav.home: 'Home'\n    nav.video: 'Video'\n    title.home: 'Welcome Home'\nhr:\n    site.name: 'Moje web stranice'\n    nav.home: 'Početna'\n    nav.video: 'Video'\n    title.home: 'Dobrodošli'\n```\n\nYou may also define the translations in a separate file per locale, where the path is relative to the theme. The following definition will source the default messages from the file **config/lang-en.yaml** inside the theme for the english locale and from the file **config/lang-fr.yaml** for the french locale.\n\n```yaml\nname: My Theme\n# [...]\n\ntranslate:\nen: config/lang-en.yaml\nfr: config/lang-fr.yaml\n```\n\nThis is an example for the **config/lang-en.yaml** file:\n\n```yaml\nsite.name: 'My Website'\nnav.home: 'Home'\nnav.video: 'Video'\ntitle.home: 'Welcome Home'\n```\n\nIn order to make these default values reflected to your frontend site, go to **Settings -\u003e Translate messages** in the backend and hit **Scan for messages**. They will also be loaded automatically when the theme is activated.\n\nThe same operation can be performed with the `translate:scan` artisan command. It may be worth including it in a deployment script to automatically fetch updated messages:\n\n```bash\nphp artisan translate:scan\n```\n    \nAdd the `--purge` option to clear old messages first:\n\n```bash \nphp artisan translate:scan --purge\n```\n    \n## Content translation\n\nThis plugin activates a feature in the CMS that allows content files to use language suffixes, for example:\n\n* **welcome.htm** will contain the content in the default language.\n* **welcome.ru.htm** will contain the content in Russian.\n* **welcome.fr.htm** will contain the content in French.\n\n## Mail template translation\n\nThis plugin activates a feature in the CMS that allows Mail template files to use language suffixes, for example:\n\n* **mail-notify.htm** will contain the mail template in the default language.\n* **mail-notify-ru.htm** will contain the mail template in Russian.\n* **mail-notify-fr.htm** will contain the mail template in French.\n\n## Model translation\n\nModels can have their attributes translated by using the `Winter.Translate.Behaviors.TranslatableModel` behavior and specifying which attributes to translate in the class.\n\n```php\nclass User extends Model\n{\n    public $implement = ['Winter.Translate.Behaviors.TranslatableModel'];\n\n    public $translatable = ['name'];\n}\n```\n\nThe attribute will then contain the default language value and other language code values can be created by using the `translateContext()` method.\n\n```php\n$user = User::first();\n\n// Outputs the name in the default language\necho $user-\u003ename;\n\n$user-\u003etranslateContext('fr');\n\n// Outputs the name in French\necho $user-\u003ename;\n```\n\nYou may use the same process for setting values.\n\n```php\n$user = User::first();\n\n// Sets the name in the default language\n$user-\u003ename = 'English';\n\n$user-\u003etranslateContext('fr');\n\n// Sets the name in French\n$user-\u003ename = 'Anglais';\n```\n\nThe `lang()` method is a shorthand version of `translateContext()` and is also chainable.\n\n```php\n// Outputs the name in French\necho $user-\u003elang('fr')-\u003ename;\n```\n\nThis can be useful inside a Twig template.\n\n```twig\n{{ user.lang('fr').name }}\n```\n\nThere are ways to get and set attributes without changing the context.\n\n```php\n// Gets a single translated attribute for a language\n$user-\u003egetAttributeTranslated('name', 'fr');\n\n// Sets a single translated attribute for a language\n$user-\u003esetAttributeTranslated('name', 'Jean-Claude', 'fr');\n```\n\n## Extending a plugin with translatable fields\n\nIf you are extending a plugin and want the added fields in the backend to be translatable, you have to use the '[backend.form.extendFieldsBefore](https://wintercms.com/docs/events/event/backend.form.extendFieldsBefore)' and tell which fields you want to be translatable by pushing them to the array.\n\n```php\npublic function boot() {\n    Event::listen('backend.form.extendFieldsBefore', function($widget) {\n        // Only apply listener to the Index controller, Page model, and when the formwidget isn't nested\n        if (\n            !($widget-\u003egetController() instanceof \\Winter\\Pages\\Controllers\\Index)\n            || !($widget-\u003emodel instanceof \\Winter\\Pages\\Classes\\Page)\n            || $widget-\u003eisNested\n        ) {\n            return;\n        }\n\n        // Add fields\n        $widget-\u003etabs['fields']['viewBag[myField]'] = [\n            'tab' =\u003e 'mytab',\n            'label' =\u003e 'myLabel',\n            'type' =\u003e 'text'\n        ];\n\n        // Translate fields\n        $translatable = [\n            'viewBag[myField]'\n        ];\n\n        // Merge the fields in the translatable array\n        $widget-\u003emodel-\u003etranslatable = array_merge($widget-\u003emodel-\u003etranslatable, $translatable);\n\n    });\n}\n```\n    \n## Theme data translation\n\nIt is also possible to translate theme customisation options. Just mark your form fields with `translatable` property and the plugin will take care about everything else:\n\n```yaml\ntabs:\n    fields:\n        website_name:\n            tab: Info\n            label: Website Name\n            type: text\n            default: Your website name\n            translatable: true\n```\n\n## Fallback attribute values\n\nBy default, untranslated attributes will fall back to the default locale. This behavior can be disabled by calling the `setTranslatableUseFallback()` method.\n\n```php\n$user = User::first();\n\n$user-\u003esetTranslatableUseFallback(false)-\u003elang('fr');\n\n// Returns NULL if there is no French translation\n$user-\u003ename;\n```\n\n## Indexed attributes\n\nTranslatable model attributes can also be declared as an index by passing the `$transatable` attribute value as an array. The first value is the attribute name, the other values represent options, in this case setting the option `index` to `true`.\n\n```php\npublic $translatable = [\n    'name',\n    ['slug', 'index' =\u003e true]\n];\n```\n\nOnce an attribute is indexed, you may use the `transWhere` method to apply a basic query to the model.\n\n```php\nPost::transWhere('slug', 'hello-world')-\u003efirst();\n```\n\nThe `transWhere` method accepts a third argument to explicitly pass a locale value, otherwise it will be detected from the environment.\n\n```php\nPost::transWhere('slug', 'hello-world', 'en')-\u003efirst();\n```\n\n## URL translation\n\nPages in the CMS support translating the URL property. Assuming you have 3 languages set up:\n\n- en: English\n- fr: French\n- ru: Russian\n\nThere is a page with the following content:\n\n```twig\nurl = \"/contact\"\n\n[viewBag]\nlocaleUrl[ru] = \"/контакт\"\n==\n\u003cp\u003ePage content\u003c/p\u003e\n```\n\nThe word \"Contact\" in French is the same so a translated URL is not given, or needed. If the page has no URL override specified, then the default URL will be used. Pages will not be duplicated for a given language.\n\n- /fr/contact - Page in French\n- /en/contact - Page in English\n- /ru/контакт - Page in Russian\n- /ru/contact - 404\n\n## URL parameter translation\n\nIt's possible to translate URL parameters by listening to the `translate.localePicker.translateParams` event, which is fired when switching languages.\n\n```php\nEvent::listen('translate.localePicker.translateParams', function($page, $params, $oldLocale, $newLocale) {\n    if ($page-\u003ebaseFileName == 'your-page-filename') {\n        return YourModel::translateParams($params, $oldLocale, $newLocale);\n    }\n});\n```\n\nIn YourModel, one possible implementation might look like this:\n\n```php\npublic static function translateParams($params, $oldLocale, $newLocale) {\n    $newParams = $params;\n    foreach ($params as $paramName =\u003e $paramValue) {\n        $records = self::transWhere($paramName, $paramValue, $oldLocale)-\u003efirst();\n        if ($records) {\n            $records-\u003etranslateContext($newLocale);\n            $newParams[$paramName] = $records-\u003e$paramName;\n        }\n    }\n    return $newParams;\n}\n```\n\n## Query string translation\n\nIt's possible to translate query string parameters by listening to the `translate.localePicker.translateQuery` event, which is fired when switching languages.\n\n```php\nEvent::listen('translate.localePicker.translateQuery', function($page, $params, $oldLocale, $newLocale) {\n    if ($page-\u003ebaseFileName == 'your-page-filename') {\n        return YourModel::translateParams($params, $oldLocale, $newLocale);\n    }\n});\n```\n\nFor a possible implementation of the `YourModel::translateParams` method look at the example under `URL parameter translation` from above.\n\n## Extend theme scan\n\n```php\nEvent::listen('winter.translate.themeScanner.afterScan', function (ThemeScanner $scanner) {\n    // ...\n});\n```\n\n## Settings model translation\n\nIt's possible to translate your settings model like any other model. To retrieve translated values use:\n\n```php\nSettings::instance()-\u003egetAttributeTranslated('your_attribute_name');\n```\n\n## Conditionally extending plugins\n\n#### Models\n\nIt is possible to conditionally extend a plugin's models to support translation by placing an `@` symbol before the behavior definition. This is a soft implement will only use `TranslatableModel` if the Translate plugin is installed, otherwise it will not cause any errors.\n\n```php\n/**\n * Blog Post Model\n */\nclass Post extends Model\n{\n\n    // [...]\n\n    /**\n     * Softly implement the TranslatableModel behavior.\n     */\n    public $implement = ['@Winter.Translate.Behaviors.TranslatableModel'];\n\n    /**\n     * @var array Attributes that support translation, if available.\n     */\n    public $translatable = ['title'];\n\n    // [...]\n\n}\n```\n\nThe back-end forms will automatically detect the presence of translatable fields and replace their controls for multilingual equivalents.\n\n#### Messages\n\nSince the Twig filter will not be available all the time, we can pipe them to the native Laravel translation methods instead. This ensures translated messages will always work on the front end.\n\n```php\n/**\n * Register new Twig variables\n * @return array\n */\npublic function registerMarkupTags()\n{\n    // Check the translate plugin is installed\n    if (!class_exists('Winter\\Translate\\Behaviors\\TranslatableModel'))\n        return;\n\n    return [\n        'filters' =\u003e [\n            '_' =\u003e ['Lang', 'get'],\n            '__' =\u003e ['Lang', 'choice'],\n        ]\n    ];\n}\n```\n\n# User Interface\n\n#### Switching locales\n\nUsers can switch between locales by clicking on the locale indicator on the right hand side of the Multi-language input. By holding the CMD / CTRL key all Multi-language Input fields will switch to the selected locale.\n\n## Integration without jQuery and Winter CMS Framework files\n\nIt is possible to use the front-end language switcher without using jQuery or the Winter CMS AJAX Framework by making the AJAX API request yourself manually. The following is an example of how to do that.\n\n```js\ndocument.querySelector('#languageSelect').addEventListener('change', function () {\n    const details = {\n        _session_key: document.querySelector('input[name=\"_session_key\"]').value,\n        _token: document.querySelector('input[name=\"_token\"]').value,\n        locale: this.value\n    }\n\n    let formBody = []\n\n    for (var property in details) {\n        let encodedKey = encodeURIComponent(property)\n        let encodedValue = encodeURIComponent(details[property])\n        formBody.push(encodedKey + '=' + encodedValue)\n    }\n\n    formBody = formBody.join('\u0026')\n\n    fetch(location.href + '/', {\n        method: 'POST',\n        body: formBody,\n        headers: {\n            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n            'X-WINTER-REQUEST-HANDLER': 'onSwitchLocale',\n            'X-WINTER-REQUEST-PARTIALS': '',\n            'X-Requested-With': 'XMLHttpRequest'\n        }\n    })\n    .then(res =\u003e res.json())\n    .then(res =\u003e window.location.replace(res.X_WINTER_REDIRECT))\n    .catch(err =\u003e console.log(err))\n})\n```\n\nThe HTML:\n\n```twig\n{{ form_open() }}\n    \u003cselect id=\"languageSelect\"\u003e\n        \u003coption value=\"none\" hidden\u003e\u003c/option\u003e\n        {% for code, name in locales %}\n            {% if code != activeLocale %}\n                \u003coption value=\"{{code}}\" name=\"locale\"\u003e{{code | upper }}\u003c/option\u003e\n            {% endif %}\n        {% endfor %}\n    \u003c/select\u003e\n{{ form_close() }}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwintercms%2Fwn-translate-plugin","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwintercms%2Fwn-translate-plugin","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwintercms%2Fwn-translate-plugin/lists"}