marcreichel/alpine-timeago

Option to set locale when cdn option is used

hendrikschneider opened this issue · 2 comments

I saw that it is possible to set the user language when using npm but how about setting it dynamically?

I am using your lib with the cdn and have the following scenario in my mind.

Scenario: The homepage offers multiple language and the user decides to switch from German to English.

Is there a way to accomplish this?

The only way I could think of is if you use the ESM distributions (including Alpine).

Your javascript could look something like this:

import Alpine from 'https://esm.run/alpinejs';
import TimeAgo from 'https://esm.run/@marcreichel/alpine-timeago';
import { de, es, enUS } from 'https://esm.run/date-fns/locale';

const myLocale = (navigator.language || navigator.userLanguage).split('-')[0];
let locale = enUS;

switch (myLocale) {
  case 'de':
    locale = de;
    break;
  case 'es':
    locale = es;
    break;
}

Alpine.plugin(TimeAgo.configure({
  locale: locale,
}))

Alpine.start();
<div x-data="{ date: new Date() }" x-timeago="date"></div>

Here's a working JSFiddle.

Thanks for the quick answer and the example.