From ad92f2cbcf4eb162c8e35fe7976091f04ab017b0 Mon Sep 17 00:00:00 2001 From: reneeb Date: Wed, 13 Sep 2023 14:32:31 +0200 Subject: [PATCH] Add new feature to Translate(): Replace/Translate parameters for translation string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E.g. in ticket history german speaking users can see the entry 'Status geändert von "new" auf "open".', so the states aren't translated. This new feature for Translate() allows to define a subroutine where those parameters (e.g. 'new' and 'open') can be translated or replaced. This is fully backwards-compatible. To use this feature, one has to pass an array ref in the translation definition. The first value has to be the translation string and the second one is a subroutine reference: package Kernel::Language::de_Parameters; use strict; use warnings; use utf8; sub Data { my = shift; ->{Translation}->{'Changed state from "%s" to "%s".'} = [ 'Status geändert von "%s" auf "%s".', \&TranslateStates, ]; return 1; } sub TranslateStates { my = ::OM->Get('Kernel::Language'); reneeb = ->Translate( reneeb ) for @_; return @_; } 1; This shows for the above mentioned string Status geändert von "neu" auf "offen".'. So it's more consistent as the same values are shown to the Agent in all places. --- Kernel/Language.pm | 8 ++++++++ scripts/test/Language.t | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/Kernel/Language.pm b/Kernel/Language.pm index aed47f7b9c4..3c442399cb2 100644 --- a/Kernel/Language.pm +++ b/Kernel/Language.pm @@ -285,8 +285,16 @@ sub Translate { $Text = $Self->{Translation}->{$Text} || $Text; + my $SubRef; + + if ( ref $Text && 'ARRAY' eq ref $Text ) { + ($Text, $SubRef) = @{ $Text || [] }; + } + return $Text if !@Parameters; + @Parameters = $SubRef->( @Parameters ) if $SubRef && ref $SubRef && 'CODE' eq ref $SubRef; + for my $Count ( 0 .. $#Parameters ) { return $Text if !defined $Parameters[$Count]; $Text =~ s/\%(s|d)/$Parameters[$Count]/; diff --git a/scripts/test/Language.t b/scripts/test/Language.t index 9106bb88837..60782f72270 100644 --- a/scripts/test/Language.t +++ b/scripts/test/Language.t @@ -238,4 +238,19 @@ for my $Test (@Tests) { ); } +{ + $LanguageObject->{Translation}->{"This is a test for a new feature in Translate(). - %s %s"} = [ 'A simple Test - %s %s', \&ReplaceParams ]; + my $Translated = $LanguageObject->Translate("This is a test for a new feature in Translate(). - %s %s", "Znuny", "rocks!"); + + $Self->Is( + $Translated, + 'A simple Test - Perl is great!', + 'Replaced params for translated string', + ); + + sub ReplaceParams { + return "Perl", "is great!"; + } +} + 1;