adonisjs / i18n

Internationalization module for AdonisJs. Supports file and database drivers
MIT License
43 stars 19 forks source link

t helper method not using switched locale #128

Closed JannieT closed 1 year ago

JannieT commented 1 year ago

Package version

1.6.0

Node.js and npm version

node v18.16.0 npm 9.5.1

Sample Code (to reproduce the issue)

Start a new Adonis project with the i18n package:

npm init adonis-ts-app@latest i18n-test
cd i18n-test
npm i @adonisjs/i18n
node ace configure @adonisjs/i18n

Add translation files:

 // resources/lang/en/all.js
{
    "works": "It works!"
}

 // resources/lang/af/all.js
{
    "works": "Dit werk!"
}

Localize the template views/welcome.edge:

<h1 class="title"> {{ t('all.works') }} </h1>

Make these changes to start/routes.ts:

Route.get("/", async (ctx) => {

  // for an RSS endpoint specifying the locale as a query string, 
  // I do not use the DetectUserLocale middleware, 
  // but set it in the controller:

  ctx.i18n.switchLocale("af");

  // formatMessage works as expected and returns the translation:
  console.log(ctx.i18n.formatMessage("all.works")); // Dit werk!

  // but the t helper method in the template renders the English
  return ctx.view.render("welcome");
});

BONUS (a sample repo to reproduce the issue)

Sample Repo

thetutlage commented 1 year ago

Hey, do you have the DetectUserLocale middleware registered?

https://docs.adonisjs.com/guides/i18n#detecting-user-locale https://docs.adonisjs.com/reference/i18n/view-helpers#i18n

JannieT commented 1 year ago

Phew! Thanks. That was it. I did not register the middleware, because I thought in my use case it can't detect the locale from the request header. But clearly it does more than meets the eye. Appreciate you sir! Your craft and graft is so inspiring.