Using Laravel-style :dot-notated replacements instead of {brackets} without messageCompiler workaround?
#2379
-
|
Does Vue I18n support Laravel-styled Since my translation files come from Laravel, I would prefer not to rewrite all placeholders to {key} just to satisfy the Vue I18n syntax. I ended up implementing a custom messageCompiler to support const i18n = createI18nPlugin({
//...
messageCompiler(message) {
if (typeof message !== 'string') {
return () => message
}
// Find keys in message
const keys = Array.from(new Set((message.match(/:\w+/g) ?? []).map(m => m.slice(1))));
if (keys.length === 0) {
return () => message;
}
// Create replacement patterns
const patterns = keys.map(key => ({
key,
re: new RegExp(`(^|[^\\w]):${key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![\\w])`, 'g')
}));
// Handle replacements - :laravel style.
return (ctx: any) => {
const values = ctx?.values
if (!values || typeof values !== 'object') {
return message;
}
let out: string = message as string;
for (const { key, re } of patterns) {
if (values[key] === undefined || values[key] === null) {
continue
}
const v = String(values[key]);
out = out.replace(re, (_m, prefix) => `${prefix}${v}`);
}
return out;
}
},
});So. Is there an officially supported way (or a recommended pattern) to handle Laravel-styled Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
The documented format is the only supported one, if you want a different format you'll need to use a custom message compiler (like you already did) or find another library that already does what you want. |
Beta Was this translation helpful? Give feedback.
The documented format is the only supported one, if you want a different format you'll need to use a custom message compiler (like you already did) or find another library that already does what you want.