From c7bdef1657849d1389383a09f1a4eea7540689bf Mon Sep 17 00:00:00 2001 From: isc-auf Date: Wed, 15 Jan 2025 20:55:40 +0100 Subject: [PATCH] feat(transloco): allow method calls with transpiled arguments in DefaultTranspiler (#830) Signed-off-by: isc-auf --- libs/transloco/src/lib/helpers.ts | 12 +++++++++++- libs/transloco/src/lib/tests/transpiler.spec.ts | 15 +++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/libs/transloco/src/lib/helpers.ts b/libs/transloco/src/lib/helpers.ts index 8d6df607..ce16429f 100644 --- a/libs/transloco/src/lib/helpers.ts +++ b/libs/transloco/src/lib/helpers.ts @@ -1,4 +1,5 @@ import { ProviderScope, Translation } from './types'; +import { getFunctionArgs } from './transloco.transpiler'; export function getValue(obj: T, path: keyof T) { if (!obj) { @@ -10,7 +11,16 @@ export function getValue(obj: T, path: keyof T) { return obj[path]; } - return (path as string).split('.').reduce((p, c) => p?.[c], obj as any); + const pathMatcher = /\s*(\w+)(?:\((.*?)\))?\s*/; + return (path as string).split('.').reduce((p, c) => { + const match = pathMatcher.exec(c); + if (p && match) { + return isDefined(match[2]) + ? p[match[1]](...getFunctionArgs(match[2])) + : p[match[1]]; + } + return undefined; + }, obj as any); } export function setValue(obj: any, prop: string, val: any) { diff --git a/libs/transloco/src/lib/tests/transpiler.spec.ts b/libs/transloco/src/lib/tests/transpiler.spec.ts index 1f212c87..2e6dceb7 100644 --- a/libs/transloco/src/lib/tests/transpiler.spec.ts +++ b/libs/transloco/src/lib/tests/transpiler.spec.ts @@ -303,6 +303,21 @@ describe('TranslocoTranspiler', () => { ).toEqual('From 1 to 10'); }); + it('should support params method calls', () => { + expect( + transpiler.transpile( + getTranspilerParams( + `Length: ${wrapParam('text.length')}, Initial: ${wrapParam('text.charAt(0)')}`, + { + params: { + text: 'Hello world', + }, + }, + ), + ), + ).toEqual('Length: 11, Initial: H'); + }); + it('should support key referencing', () => { const lang = flatten({ ab: `a b ${wrapParam('cd')}`,