Internationalization with Laravel's Translation #718
pronist
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello! While attempting to create a static site with Jigsaw, I spent a lot of time thinking about internationalization, and I'd like to share the approach I used.
Installation
mkdir my-app cd my-app composer require tightenco/jigsaw vendor/bin/jigsaw init npm installInternationalization
We use Laravel Translation for internationalization.
Since we will be creating a dedicated class for handling internationalization, add PSR-4 to
composer.json.Create an app directory for the classes.
Now let's create the I18n class for internationalization and the
langdirectory for storing language settings.I18n
The
I18nclass is responsible for internationalization, retrieving values for specific keys from the language files. It also facilitates translation withI18n::trans().helpers.php
For convenience, let's create a
trans()function inhelpers.php. Note thattrans()accesses the$page->localevariable globally or for collection pages.Lang
Let's create two language files for English and Korean.
lang/en/app.php
lang/ko/app.php
Locale Collection
The
LocaleCollectionis a dedicated collection class for managing internationalization and locale settings.LocaleCollection::create()generates a collection for the provided locales and sets keys likelocaleanddefaultLocale. One important note: when setting the default locale, the resulting build for the default locale does not place the collection in a separate folder. This behavior is implemented inLocaleCollection::getPath().Scopeable
Scopeableis a trait that allows pages to have a scope, used for implementing nested collections. An important point inScopeableis thatScopeable::getScopedCollection()adds variables for nested collections to the page and appends each item in the map.config.php
Now, return to the configuration and specify the collection for internationalization.
Collections
Before creating the multilingual collections and pages, let's create a layout for our example. The default
index.blade.phpis not needed.source/_layouts/post.blade.php
Create the collections and files for multilingual content.
source/_en/index.blade.php
Note that the index accesses the nested collection via
$page->posts.source/_en/posts/2024-12-01-hello.md
You can add a scope setting if necessary.
source/_ko/index.blade.php
source/_ko/posts/2024-12-01-hello.md
source/_layouts/main.blade.php
Internationalization can be handled directly in the layout.
Build
Beta Was this translation helpful? Give feedback.
All reactions