Log-Report-Template-1.04/0000755000175000001440000000000015102365753015726 5ustar00markovusers00000000000000Log-Report-Template-1.04/t/0000755000175000001440000000000015102365753016171 5ustar00markovusers00000000000000Log-Report-Template-1.04/t/lexicons/0000755000175000001440000000000015102365753020015 5ustar00markovusers00000000000000Log-Report-Template-1.04/t/lexicons/first.utf-8.po0000644000175000001440000000155115102365753022450 0ustar00markovusers00000000000000#. Header generated with Log::Report::Lexicon::POT 0.0 msgid "" msgstr "" "Project-Id-Version: first 0.01\n" "Report-Msgid-Bugs-To:\n" "POT-Creation-Date: 2017-06-21 20:03+0200\n" "PO-Revision-Date: 2025-11-04 13:04+0100\n" "Last-Translator:\n" "Language-Team:\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n!=1);\n" #: t/templates/root.tt:7 #, fuzzy msgid "Dear visitor," msgstr "" #: t/templates/root.tt:13 #, fuzzy msgid "" "The FILTER test, number {count},\n" "is here" msgstr "" #: t/templates/root.tt:11 #, fuzzy msgid "This is the {count TH} test" msgstr "" #: t/templates/root.tt:12 #, fuzzy msgid "This is the {count TH} test, in a pipe" msgstr "" #: t/templates/root.tt:17 #, fuzzy msgid "" "multi-line cleanup\n" "this mess, as HTML\n" "\n" "accepts\n" msgstr "" Log-Report-Template-1.04/t/lexicons/second.utf-8.po0000644000175000001440000000073715102365753022601 0ustar00markovusers00000000000000#. Header generated with Log::Report::Lexicon::POT 0.0 msgid "" msgstr "" "Project-Id-Version: second 0.01\n" "Report-Msgid-Bugs-To:\n" "POT-Creation-Date: 2017-06-21 20:03+0200\n" "PO-Revision-Date: 2025-11-04 13:04+0100\n" "Last-Translator:\n" "Language-Team:\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=utf-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n!=1);\n" #: t/templates/root.tt:15 #, fuzzy msgid "second table" msgstr "" Log-Report-Template-1.04/t/20examples.t0000644000175000001440000000126015102365307020330 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test that (some of) the examples work. use warnings; use strict; use Test::More; use Log::Report; use_ok 'Log::Report::Template'; # The modifiers are loaded automagically my $templater = Log::Report::Template->new; isa_ok $templater, 'Log::Report::Template'; $templater->addTextdomain(name => 'default', lexicon => '.'); ### test chaining IF my $output = ''; $templater->process(\'[% a = b; IF a %]YES[%END%]', {b => 1}, \$output) or $templater->error; is $output, "YES", 'chain yes'; $output = ''; $templater->process(\'[% a = b; IF a %]YES[%ELSE%]NO[%END%]', {b => 0}, \$output) or $templater->error; is $output, "NO", 'chain no'; done_testing; Log-Report-Template-1.04/t/10templater.t0000644000175000001440000000364315102365307020515 0ustar00markovusers00000000000000#!/usr/bin/env perl # Check the creation of the templater use warnings; use strict; use Test::More; use Log::Report; use File::Basename qw(dirname); dispatcher close => 'default'; (my $incl) = grep -d, 't/templates', 'templates'; $incl or die "where are my templates?"; my $lexicon = dirname($incl) .'/lexicons'; -d $lexicon or mkdir $lexicon or die "$lexicon: $!"; use_ok 'Log::Report::Template'; my $templater = Log::Report::Template->new(INCLUDE_PATH => $incl); isa_ok $templater, 'Log::Report::Template'; ### Construct textdomain 'first' my $first = $templater->addTextdomain(name => 'first', lexicon => $lexicon); isa_ok $first, 'Log::Report::Template::Textdomain'; is $first->function, 'loc', 'default function'; ok $first->expectedIn($incl), 'expectedIn'; my $f2 = textdomain 'first'; ok defined $f2, 'recover domain'; is $first, $f2; #dispatcher close => 'default'; eval { $templater->addTextdomain(name => 'first') }; is $@, "error: extension to domain 'first' already exists\n", 'no redefine'; eval { $templater->addTextdomain(name => 'error1', only_in_directory => '/tmp')}; is $@, "error: directory /tmp not in INCLUDE_PATH, used by addTextdomain(only_in_directory)\n", 'outside INCLUDE_PATH'; #eval { $templater->addTextdomain(name => 'error2') }; #is $@, "error: textdomain 'error2' does not specify the lexicon directory\n", 'no lexicon'; eval { $templater->addTextdomain(name => 'error3', lexicon => $lexicon) }; is $@, "error: translation function 'loc' already in use by textdomain 'first'\n", 'same function again'; ### Construct textdomain 'second' my $second = $templater->addTextdomain ( name => 'second' , lexicon => $lexicon , translation_function => 'S' , only_in_directory => $incl ); isa_ok $second, 'Log::Report::Template::Textdomain'; is $second->function, 'S', 'function S'; ok $second->expectedIn($incl), 'expectedIn'; ok ! $second->expectedIn('/tmp'), 'not expectedIn'; done_testing; Log-Report-Template-1.04/t/14missing.t0000644000175000001440000000241015102365307020164 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the additional modifiers. use warnings; use strict; use Test::More; use Log::Report; use_ok 'Log::Report::Template'; # The modifiers are loaded automagically my $templater = Log::Report::Template->new; isa_ok $templater, 'Log::Report::Template'; $templater->addTextdomain(name => 'default', lexicon => '.'); ### the usual my $output = ''; $templater->process(\'[% loc("Present {a}", a => b) %]', {b => 1}, \$output) or $templater->error; is $output, "Present 1", 'usual'; ### undef $output = ''; $templater->process(\'[% loc("Present {a}", a => b) %]', {b => undef}, \$output) or $templater->error; # Template Toolkit translates 'undef b' into an empty string :-( is $output, "Present ", 'undef'; ### missing dispatcher close => 'default'; $output = ''; try { $templater->process(\'[% loc("Present {a}") %]', {}, \$output) or $templater->error }; (my $warning) = $@->exceptions; is $warning, "warning: Missing key 'a' in format 'Present {a}', in input text\n"; is $output, "Present undef", 'missing'; ### missing, but found in environment $output = ''; $templater->process(\'[% loc("Present {a}") %]', {a => 42}, \$output) or $templater->error; is $output, "Present 42", 'magically collected from stash'; done_testing; Log-Report-Template-1.04/t/12filters.t0000644000175000001440000000176615102365307020176 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the additional filters. use warnings; use strict; use Test::More; use_ok 'Log::Report::Template'; my $templater = Log::Report::Template->new; isa_ok $templater, 'Log::Report::Template'; sub fill($$) { my ($input, $filter) = @_; my $templ = qq{[% "$input" | $filter %]}; my $output = ''; $templater->process(\$templ, {}, \$output) or die $templater->error; $output; } ### cols is fill("a", "cols"), "a", 'cols default'; is fill("a\tb\tc", "cols"), "abc"; is fill("a", "cols('th')"), "a", 'cols first form'; is fill("a\tb\tc", "cols('th', 'td')"), "abc"; is fill("a", "cols('\$1')"), "a" , 'cols second form'; is fill("a\tb\tc", "cols('\$3\$1')"), "ca"; ### br is fill("a\n", "br"), "a
\n", 'br'; is fill("a\nb\n", "br"), "a
\nb
\n", 'br simple'; is fill(" \t\na\n\n \n\nb \n\n", "br"), "a
\nb
\n", 'br cleanup'; done_testing; Log-Report-Template-1.04/t/13modifiers.t0000644000175000001440000000060215102365307020474 0ustar00markovusers00000000000000#!/usr/bin/env perl # Test the additional modifiers. use warnings; use strict; use Test::More; use Log::Report mode => 'DEBUG'; use File::Basename qw(dirname); use_ok 'Log::Report::Template'; # The modifiers are loaded automagically my $templater = Log::Report::Template->new; isa_ok $templater, 'Log::Report::Template'; ### oops, there are none to be tested yet ;-) done_testing; Log-Report-Template-1.04/t/01use.t0000644000175000001440000000147615102365307017316 0ustar00markovusers00000000000000#!/usr/bin/env perl use warnings; use strict; use lib 'lib'; use Test::More; # The versions of the following packages are reported to help understanding # the environment in which the tests are run. This is certainly not a # full list of all installed modules. my @show_versions = qw/Test::More Log::Report Log::Report::Optional Log::Report::Lexicon String::Print Template /; foreach my $package (@show_versions) { eval "require $package"; no strict 'refs'; my $report = !$@ ? "version ". (${"$package\::VERSION"} || 'unknown') : $@ =~ m/^Can't locate/ ? "not installed" : "reports error"; warn "$package $report\n"; } require_ok('Log::Report::Template'); require_ok('Log::Report::Template::Extract'); require_ok('Log::Report::Template::Textdomain'); done_testing; Log-Report-Template-1.04/t/40extract.t0000644000175000001440000000435315102365307020174 0ustar00markovusers00000000000000#!/usr/bin/env perl # Try to extract all translation strings from templates use warnings; use strict; use File::Temp qw/tempdir/; use Test::More; use Log::Report; # mode => 'DEBUG'; use Log::Report::Lexicon::POT; use Log::Report::Template::Extract; use constant MSGIDS => 12; # see after __END__ my @expect_pos = split /\n/, <<'_EXPECT'; first second third fourth fifth six six six %d seven eight nine tenth {a} eleven twelve {b} _EXPECT chomp $expect_pos[-1]; cmp_ok(scalar @expect_pos, '==', MSGIDS); my %expect_pos = map +($_ => 1), @expect_pos; $expect_pos{''} = 1; # header BEGIN { plan tests => 15 + MSGIDS*3; } my $lexicon = tempdir CLEANUP => 1; my $extr = Log::Report::Template::Extract->new ( lexicon => $lexicon , domain => 'my-domain' , pattern => 'TT2-loc' ); ok(defined $extr, 'created parser'); isa_ok($extr, 'Log::Report::Template::Extract'); my $found = $extr->process( __FILE__ ); # yes, this file! cmp_ok($found, '==', MSGIDS); $extr->write; my @potfns = $extr->index->list('my-domain'); cmp_ok(scalar @potfns, '==', 1, "one file created"); my $potfn = shift @potfns; ok(defined $potfn); ok(-s $potfn, "produced file $potfn has size"); #system "cat $potfn"; my $pot = Log::Report::Lexicon::POT->read($potfn, charset => 'utf-8'); ok(defined $pot, 'read translation table'); my @pos = $pot->translations('ACTIVE'); ok(@pos > 0); # (+1 for the header) cmp_ok(scalar @pos, '==', MSGIDS+1, 'correct number tests'); cmp_ok(scalar @pos, '==', scalar $pot->translations); # all active my %msgids; for my $po (@pos) { my $msgid = $po->msgid; ok(defined $msgid, "processing '$msgid'"); ok(!defined $msgids{$msgid}, 'check not double'); $msgids{$msgid}++; ok(delete $expect_pos{$msgid}, 'was expected'); } cmp_ok(scalar keys %expect_pos, '==', 0, "all msgids found"); warn "NOT FOUND: $_\n" for keys %expect_pos; __END__ Here, the example template starts [%loc("first")%] [%loc("second")%] [%loc('third')%] [% loc ( 'fourth' ) %] [% loc ( 'fifth' , params ) %] [%xloc('not found')%] [%loc('six six six')%] [% loc('%d seven|%d sevens', 7) %] [% INCLUDE header.tt title = loc("eight") loc ('nine' ) css =loc( 'tenth' ) %] [% '{a} eleven' | loc(a => 3) %] [%| loc(b=>4) %]twelve {b}[%END%] Log-Report-Template-1.04/t/templates/0000755000175000001440000000000015102365753020167 5ustar00markovusers00000000000000Log-Report-Template-1.04/t/templates/root.tt0000644000175000001440000000072515102365307021522 0ustar00markovusers00000000000000 [% title %]

[% loc("Dear visitor,") %]
[% "" | html %]
[% loc("This is the {count TH} test", count => 1) %]
[% | loc(count => 2) %]This is the {count TH} test, in a pipe[% END %]
[% FILTER loc(count => 3) %]The FILTER test, number {count}, is here[% END %]
[% S("second table") %] [% FILTER loc %] multi-line cleanup this mess, as HTML accepts [% END %] Log-Report-Template-1.04/t/41double.t0000644000175000001440000000224015102365307017766 0ustar00markovusers00000000000000#!/usr/bin/env perl # Check the extraction of po-tables from two separate domains merged # in the same template files. use warnings; use strict; use Test::More; # use Log::Report mode => 'DEBUG'; # DEBUG to see stats use File::Basename qw(dirname); (my $incl) = grep -d, 't/templates', 'templates'; $incl or die "where are my templates?"; my $lexicon = dirname($incl) .'/lexicons'; -d $lexicon or mkdir $lexicon or die "$lexicon: $!"; ### Construct templater (tested in t/10templater.t) use_ok 'Log::Report::Template'; my $templater = Log::Report::Template->new(INCLUDE_PATH => $incl, # DEBUG => 255 ); isa_ok $templater, 'Log::Report::Template'; ### Define first, default function loc() my $first = $templater->addTextdomain(name => 'first', lexicon => $lexicon); isa_ok $first, 'Log::Report::Template::Textdomain'; is $first->name, 'first'; #dispatcher close => 'default'; ### Define second, translation function S() my $second = $templater->addTextdomain( name => 'second', translation_function => 'S', only_in_directory => $incl, lexicon => $lexicon, ); ### Extract from the template files $templater->extract; done_testing; Log-Report-Template-1.04/lib/0000755000175000001440000000000015102365753016474 5ustar00markovusers00000000000000Log-Report-Template-1.04/lib/Log/0000755000175000001440000000000015102365753017215 5ustar00markovusers00000000000000Log-Report-Template-1.04/lib/Log/Report/0000755000175000001440000000000015102365753020470 5ustar00markovusers00000000000000Log-Report-Template-1.04/lib/Log/Report/Template/0000755000175000001440000000000015102365753022243 5ustar00markovusers00000000000000Log-Report-Template-1.04/lib/Log/Report/Template/Extract.pm0000644000175000001440000001136515102365751024217 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.04. # The POD got stripped from this file by OODoc version 3.05. # For contributors see file ChangeLog. # This software is copyright (c) 2017-2025 by Mark Overmeer. # This is free software; you can redistribute it and/or modify it under # the same terms as the Perl 5 programming language system itself. # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later #oodist: *** DO NOT USE THIS VERSION FOR PRODUCTION *** #oodist: This file contains OODoc-style documentation which will get stripped #oodist: during its release in the distribution. You can use this file for #oodist: testing, however the code of this development version may be broken! package Log::Report::Template::Extract;{ our $VERSION = '1.04'; } use base 'Log::Report::Extract'; use warnings; use strict; use Log::Report 'log-report-template'; use Log::Report::Template::Textdomain (); sub _normalized_ws($) { Log::Report::Template::Textdomain::_normalized_ws($_[0]) } #-------------------- sub init($) { my ($self, $args) = @_; $self->SUPER::init($args); $self->{LRTE_domain} = $args->{domain} or error __"template extract requires explicit domain"; $self->{LRTE_pattern} = $args->{pattern}; $self; } #-------------------- sub domain() { $_[0]->{LRTE_domain} } sub pattern() { $_[0]->{LRTE_pattern} } #-------------------- sub process($@) { my ($self, $fn, %opts) = @_; my $charset = $opts{charset} || 'utf-8'; info __x"processing file {file} in {charset}", file => $fn, charset => $charset; my $pattern = $opts{pattern} || $self->pattern or error __"need pattern to scan for, either via new() or process()"; # Slurp the whole file open my $in, "<:encoding($charset)", $fn or fault __x"cannot read template from {file}", file => $fn; undef $/; my $text = $in->getline; $in->close; my $domain = $self->domain; $self->_reset($domain, $fn); if(ref $pattern eq 'CODE') { return $pattern->($fn, \$text); } elsif($pattern =~ m/^TT([12])-(\w+)$/) { return $self->scanTemplateToolkit($1, $2, $fn, \$text); } else { error __x"unknown pattern {pattern}", pattern => $pattern; } (); } sub _no_escapes_in($$$$) { my ($msgid, $plural, $fn, $linenr) = @_; return if $msgid !~ /\&\w+\;/ && (defined $plural ? $plural !~ /\&\w+\;/ : 1); $msgid .= "|$plural" if defined $plural; warning __x"msgid '{msgid}' contains html escapes, don't do that. File {file} line {linenr}", msgid => $msgid, file => $fn, linenr => $linenr; } sub scanTemplateToolkit($$$$) { my ($self, $version, $function, $fn, $textref) = @_; # Split the whole file on the pattern in four fragments per match: # (text, leading, needed trailing, text, leading, ...) # f.i. ('', '[% loc("', 'some-msgid', '", params) %]', ' more text') my @frags = $version==1 ? split(/[\[%]%(.*?)%[%\]]/s, $$textref) : split(/\[%(.*?)%\]/s, $$textref); my $domain = $self->domain; my $linenr = 1; my $msgs_found = 0; # pre-compile the regexes, for performance my $pipe_func_block = qr/^\s*(?:\|\s*|FILTER\s+)$function\b/; my $msgid_pipe_func = qr/^\s*(["'])([^\r\n]+?)\1\s*\|\s*$function\b/; my $func_msgid_multi = qr/(\b$function\s*\(\s*)(["'])([^\r\n]+?)\2/s; while(@frags > 2) { my ($skip_text, $take) = (shift @frags, shift @frags); $linenr += $skip_text =~ tr/\n//; if($take =~ $pipe_func_block) { # [% | loc(...) %] $msgid [%END%] or [% FILTER ... %]...[% END %] if(@frags < 2 || $frags[1] !~ /^\s*END\s*$/) { error __x"template syntax error, no END in {fn} line {line}", fn => $fn, line => $linenr; } my $msgid = $frags[0]; # next content my $plural = $msgid =~ s/\|(.*)// ? $1 : undef; _no_escapes_in $msgid, $plural, $fn, $linenr; $self->store($domain, $fn, $linenr, _normalized_ws($msgid), _normalized_ws($plural)); $msgs_found++; $linenr += $take =~ tr/\n//; next; } if($take =~ $msgid_pipe_func) { # [% $msgid | loc(...) %] my $msgid = $2; my $plural = $msgid =~ s/\|(.*)// ? $1 : undef; _no_escapes_in $msgid, $plural, $fn, $linenr; $self->store($domain, $fn, $linenr, $msgid, $plural); $msgs_found++; $linenr += $take =~ tr/\n//; next; } # loc($msgid, ...) form, can appear more than once my @markup = split $func_msgid_multi, $take; while(@markup > 4) { # quads with text, call, quote, msgid $linenr += ($markup[0] =~ tr/\n//) + ($markup[1] =~ tr/\n//); my $msgid = $markup[3]; my $plural = $msgid =~ s/\|(.*)// ? $1 : undef; _no_escapes_in $msgid, $plural, $fn, $linenr; $self->store($domain, $fn, $linenr, $msgid, $plural); $msgs_found++; splice @markup, 0, 4; } $linenr += $markup[-1] =~ tr/\n//; # rest of container } # $linenr += $frags[-1] =~ tr/\n//; # final page fragment not needed $msgs_found; } #-------------------- 1; Log-Report-Template-1.04/lib/Log/Report/Template/Textdomain.pm0000644000175000001440000001211615102365751024714 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.04. # The POD got stripped from this file by OODoc version 3.05. # For contributors see file ChangeLog. # This software is copyright (c) 2017-2025 by Mark Overmeer. # This is free software; you can redistribute it and/or modify it under # the same terms as the Perl 5 programming language system itself. # SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later #oodist: *** DO NOT USE THIS VERSION FOR PRODUCTION *** #oodist: This file contains OODoc-style documentation which will get stripped #oodist: during its release in the distribution. You can use this file for #oodist: testing, however the code of this development version may be broken! package Log::Report::Template::Textdomain;{ our $VERSION = '1.04'; } use base 'Log::Report::Domain'; use warnings; use strict; use Log::Report 'log-report-template'; use Log::Report::Message (); use Scalar::Util qw/weaken/; #-------------------- sub init($) { my ($self, $args) = @_; $self->SUPER::init($args)->_initMe($args); } sub _initMe($) { my ($self, $args) = @_; if(my $only = $args->{only_in_directory}) { my @only = ref $only eq 'ARRAY' ? @$only : $only; my $dirs = join '|', map "\Q$_\E", @only; $self->{LRTT_only_in} = qr!^(?:$dirs)(?:$|/)!; } $self->{LRTT_function} = $args->{translation_function} || 'loc'; $self->{LRTT_lexicon} = $args->{lexicon}; $self->{LRTT_lang} = $args->{lang}; $self->{LRTT_templ} = $args->{templater} or panic "Requires templater"; weaken $self->{LRTT_templ}; $self; } sub upgrade($%) { my ($class, $domain, %args) = @_; ref $domain eq 'Log::Report::Domain' or error __x"extension to domain '{name}' already exists", name => $domain->name; (bless $domain, $class)->_initMe(\%args); } #-------------------- sub templater() { $_[0]->{LRTT_templ} } sub function() { $_[0]->{LRTT_function} } sub lexicon() { $_[0]->{LRTT_lexicon} } sub expectedIn($) { my ($self, $fn) = @_; my $only = $self->{LRTT_only_in} or return 1; $fn =~ $only; } sub lang() { $_[0]->{LRTT_lang} } #-------------------- sub translateTo($) { my ($self, $lang) = @_; $self->{LRTT_lang} = $lang; } sub translationFunction($) { my ($self, $service) = @_; my $context = $service->context; # Prepare as much and fast as possible, because it gets called often! sub { # called with ($msgid, @positionals, [\%params]) my $msgid = shift; my $params = @_ && ref $_[-1] eq 'HASH' ? pop @_ : {}; my $plural = $msgid =~ s/\|(.*)// ? $1 : undef; if(defined $plural && ! defined $params->{_count}) { @_ or error __x"no counting positional for '{msgid}'", msgid => $msgid; $params->{_count} = shift; } @_ and error __x"superfluous positional parameters for '{msgid}'", msgid => $msgid; Log::Report::Message->new( _msgid => $msgid, _plural => $plural, _domain => $self, %$params, _stash => $context->{STASH}, _expand => 1, )->toString($self->lang); }; } # Larger HTML blocks are fragile in blanks. We remove all superfluous blanks from the # msgid, which will break translation of

 blocks :-)
sub _normalized_ws($)      # Code shared with ::Extract
{	defined $_[0] or return undef;
	$_[0] =~ s/[ \t]+/ /gr # remove blank repetition
		=~ s/^ //gmr     # no blanks in the beginning of the line
		=~ s/\A\n+//r    # no leading blank lines
		=~ s/\n+\z/\n/r; # no trailing blank lines;
}

sub translationFilter()
{	my $self   = shift;

	# Prepare as much and fast as possible, because it gets called often!
	# A TT filter can be either static or dynamic.  Dynamic filters need to
	# implement a "a factory for static filters": a sub which produces a
	# sub which does the real work.
	sub {
		my $context = shift;
		my $params  = @_ && ref $_[-1] eq 'HASH' ? pop @_ : {};
		$params->{_count} = shift if @_;
		$params->{_error} = 'too many' if @_;   # don't know msgid yet

		sub { # called with $msgid (template container content) only, the
			# parameters are caught when the factory produces this sub.
			my $msgid  = shift;
			my $plural = $msgid =~ s/\|(.*)// ? $1 : undef;
			defined $plural || ! defined $params->{_count}
				or error __x"message does not contain counting alternatives in '{msgid}'", msgid => $msgid;

			! defined $plural || defined $params->{_count}
				or error __x"no counting positional for '{msgid}'", msgid => $msgid;

			! $params->{_error}
				or error __x"superfluous positional parameters for '{msgid}'", msgid => $msgid;

			Log::Report::Message->new(_msgid => _normalized_ws($msgid), _plural => _normalized_ws($plural), _domain => $self,
				%$params, _stash => $context->{STASH}, _expand => 1,
			)->toString($self->lang);
		}
	};
}

sub _reportMissingKey($$)
{	my ($self, $sp, $key, $args) = @_;

	# Try to grab the value from the stash.  That's a major advantange
	# of TT over plain Perl: we have access to the variable namespace.

	my $stash = $args->{_stash};
	if($stash)
	{	my $value = $stash->get($key);
		return $value if defined $value && length $value;
	}

	warning __x"Missing key '{key}' in format '{format}', in {use //template}",
		key => $key, format => $args->{_format}, use => $stash->{template}{name};

	undef;
}

1;
Log-Report-Template-1.04/lib/Log/Report/Template/Textdomain.pod0000644000175000001440000001463215102365751025067 0ustar00markovusers00000000000000=encoding utf8

=head1 NAME

Log::Report::Template::Textdomain - template translation with one domain

=head1 INHERITANCE

 Log::Report::Template::Textdomain
   is a Log::Report::Domain
   is a Log::Report::Minimal::Domain

=head1 SYNOPSIS

  my $templater = Log::Report::Template->new(...);
  my $domain    = $templater->addTextdomain(%options);

=head1 DESCRIPTION

Manage one translation domain for L.

Extends L<"DESCRIPTION" in Log::Report::Domain|Log::Report::Domain/"DESCRIPTION">.

=head1 METHODS

Extends L<"METHODS" in Log::Report::Domain|Log::Report::Domain/"METHODS">.

=head2 Constructors

Extends L<"Constructors" in Log::Report::Domain|Log::Report::Domain/"Constructors">.

=over 4

=item $class-EB(%options)

Inherited, see L

 -Option              --Defined in                  --Default
  lang                                                undef
  lexicon                                             undef
  name                  Log::Report::Minimal::Domain  
  only_in_directory                                   undef
  templater                                           
  translation_function                                'loc'

=over 2

=item lang => LANGUAGES

[1.01] Initial language to translate to.  Usually, this language which change
for each user connection via L.

=item lexicon => DIRECTORY

=item name => STRING

=item only_in_directory => DIRECTORY|ARRAY

The textdomain can only be used in the indicated directories: if found
anywhere else, it's an error.  When not specified, the function is
allowed everywhere.

=item templater => Log::Report::Template-object

=item translation_function => STRING

The name of the function as used in the template to call for translation.
See L.  It must be unique over all text-domains used.

=back

=item $class-EB($domain, %options)

Upgrade a base class L-object into an Template
domain.

This is a bit akward process, needed when one of the code packages
uses the same domain as the templating system uses.  The generic domain
configuration stays intact.

=back

=head2 Attributes

Extends L<"Attributes" in Log::Report::Domain|Log::Report::Domain/"Attributes">.

=over 4

=item $obj-EB(%options)

Inherited, see L

=item $obj-EB()

Inherited, see L

=item $obj-EB($filename)

Return C when the function name which relates to this domain is
allowed to be used for the indicated file.  The msgid extractor will warn
when there is no match.

=item $obj-EB()

Returns the name of the function which is used for translations.

=item $obj-EB()

Inherited, see L

=item $obj-EB()

The language we are going to translate to.  Change this with L
for this domain, or better L.

=item $obj-EB()

Directory where the translation tables are kept.

=item $obj-EB()

Inherited, see L

=item $obj-EB()

Inherited, see L

=item $any-EB($filename)

Inherited, see L

=item $obj-EB()

The L object which is using this textdomain.

=item $obj-EB()

Inherited, see L

=back

=head2 Translating

Extends L<"Translating" in Log::Report::Domain|Log::Report::Domain/"Translating">.

=over 4

=item $obj-EB()

Inherited, see L

=item $obj-EB( $msgid, [$args] )

Inherited, see L

=item $obj-EB(STRING|HASH|ARRAY|PAIRS)

Inherited, see L

=item $obj-EB($message, $language)

Inherited, see L

=item $obj-EB($lang)

Set the language to translate to for C<$lang>, for this domain only.  This may
be useful when various text domains do not support the same destination languages.
But in general, you can best use L.

=item $obj-EB()

This method returns a CODE which is able to handle a call for
translation by Template Toolkit.

=item $obj-EB(STRING|HASH|ARRAY|PAIRS)

Inherited, see L

=back

=head1 DETAILS

Extends L<"DETAILS" in Log::Report::Domain|Log::Report::Domain/"DETAILS">.

=head1 DIAGNOSTICS

=over 4

=item Warning: Missing key '$key' in format '$format', file $use

Cast by C

=item Warning: Missing key '$key' in format '$format', in $use //template

Cast by C

=item Fault: cannot open JSON file for context at $fn: $!

Cast by C

=item Error: extension to domain '$name' already exists

Cast by C

=item Error: message does not contain counting alternatives in '$msgid'

Cast by C

=item Error: no counting positional for '$msgid'

Cast by C

=item Error: no counting positional for '$msgid'

Cast by C

=item Error: superfluous positional parameters for '$msgid'

Cast by C

=item Error: superfluous positional parameters for '$msgid'

Cast by C

=item Error: the native_language '$locale' is not a valid locale

Cast by C

=item Error: unsupported context file type for $fn

Cast by C

=item Error: you need to configure context_rules before setContext

Cast by C

=back

=head1 SEE ALSO

This module is part of Log-Report-Template version 1.04,
built on November 04, 2025. Website: F

=head1 LICENSE

For contributors see file ChangeLog.

This software is copyright (c) 2017-2025 by Mark Overmeer.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Log-Report-Template-1.04/lib/Log/Report/Template/Extract.pod0000644000175000001440000002075015102365751024363 0ustar00markovusers00000000000000=encoding utf8

=head1 NAME

Log::Report::Template::Extract - collect translatable strings from template files

=head1 INHERITANCE

 Log::Report::Template::Extract
   is a Log::Report::Extract

=head1 SYNOPSIS

  # Added Log-Report-Template v0.90
  # First use of this module: extract msgids from various kinds
  # of text-files, usually web templates.
  # See script "xgettext-perl" for standard wrapper script

  my $extr = Log::Report::Template::Extract->new(
    lexicon => '/usr/share/locale',
    domain  => 'my-web-site',
    pattern => 'TT2-loc',
  );
  $extr->process('website/page.html');  # many times
  $extr->showStats;
  $extr->write;

  # Second use: connect to Template::Toolkit
  # See DETAILS chapter below

  [% loc("Greetings {name},", name => client.name) %]
  [% | loc(name => client.name) %]Greetings {name}[% END %]
  [% 'Greetings {name}' | loc(name => client.name) %]

=head1 DESCRIPTION

This module helps maintaining the POT files which list translatable
strings from template files (or other flat text files) by updating the
list of message-ids which are kept in them.

After initiation, the L method needs to be called for each file
in the domain  and the existing PO files will get updated accordingly.

If no translations exist yet, one C<$textdomain.po> file will be
created as point to start.  Copy that file into C<$textdomain/$lang.po>

Extends L<"DESCRIPTION" in Log::Report::Extract|Log::Report::Extract/"DESCRIPTION">.

=head1 METHODS

Extends L<"METHODS" in Log::Report::Extract|Log::Report::Extract/"METHODS">.

=head2 Constructors

Extends L<"Constructors" in Log::Report::Extract|Log::Report::Extract/"Constructors">.

=over 4

=item $class-EB(%options)

Z<>

 -Option --Defined in          --Default
  charset  Log::Report::Extract  'utf-8'
  domain                         
  lexicon  Log::Report::Extract  
  pattern                        >

=over 2

=item charset => STRING

=item domain => DOMAIN

There is no syntax for specifying domains in templates (yet), so you
must be explicit about the collection we are making now.

=item lexicon => DIRECTORY

=item pattern => PREDEFINED|CODE

See the DETAILS section below for a detailed explenation.

=back

=back

=head2 Accessors

Extends L<"Accessors" in Log::Report::Extract|Log::Report::Extract/"Accessors">.

=over 4

=item $obj-EB($domain, $pot, %options)

Inherited, see L

=item $obj-EB()

Inherited, see L

=item $obj-EB()

Z<>

=item $obj-EB()

Inherited, see L

=item $obj-EB()

Inherited, see L

=item $obj-EB()

Z<>

=item $obj-EB($domain)

Inherited, see L

=back

=head2 Processors

Extends L<"Processors" in Log::Report::Extract|Log::Report::Extract/"Processors">.

=over 4

=item $obj-EB(%options)

Inherited, see L

=item $obj-EB($filename, %options)

Update the domains mentioned in the C<$filename>.  All textdomains defined
in the file will get updated automatically, but not written before
all files where processed.
Improves base, see L

 -Option --Default
  charset  'utf-8'
  pattern  

=over 2

=item charset => STRING

The character encoding used in this template file.

=item pattern => PREDEFINED|CODE

Read the DETAILS section about this.

=back

=item $obj-EB( [$domains] )

Inherited, see L

=item $obj-EB( $domain, $filename, $linenr, $context, $msg, [$msg_plural] )

Inherited, see L

=item $obj-EB( [$domain], %options )

Inherited, see L

=back

=head1 DETAILS

=head2 Scan Patterns

Various template systems use different conventions for denoting strings
to be translated.

=head3 Predefined for Template-Toolkit

There is not a single convention for translations in C
(see Template), so you need to specify which version TT you use and
which function name you want to use.  In extreme cases, you may even build
separate translation tables by simply providing using functions.

For instance

  pattern => 'TT2-loc'

will scan for

  [% loc("msgid", key => value, ...) %]
  [% loc('msgid', key => value, ...) %]
  [% loc("msgid|plural", count, key => value, ...) %]

  [% INCLUDE
       title = loc('something')
   %]

  [% | loc(n => name) %]hi {n}[% END %]
  [% 'hi {n}' | loc(n => name) %]

For C, the brackets can either be '[%...%]' or '%%...%%'.  The function
name is treated case-sensitive.  Some people prefer 'l()' or 'L()'.

The code needed

  # during initiation of the webserver, once in your script (before fork)
  my $lexicons   = 'some-directory-for-translation-tables';
  my $pots = Log::Report::Translator::POT->new(lexicons => $lexicons);

  my $templater  = Log::Report::Template->new(...);
  my $domain     = $templater->addTextdomain(
      name     => $domainname,
      function => 'loc',
  );
  $domain->configure(translator => $pots);

  # part of the processing per page
  $vars{translate_to} = 'nl_NL.utf8';
  $templater->process($template, \%vars, \$output);

To generate the pod tables, run in the shell something like

  xgettext-perl -p $lexicons --template TT2-loc \
      --domain $textdomain  $templates_dir

If you want to implement your own extractor --to avoid C--
you need to run something like this:

  my $extr = Log::Report::Template::Extract->new(
    lexicon => $output,
    charset => 'utf-8',
    domain  => $domain,
    pattern => 'TT2-loc',
  );
  $extr->process($_) for @filenames;
  $extr->write;

=head2 Use in combination with contexts

This example extends the previous with using context sensitive translations,
as implemented by L.

Let's say that the translation of some of the sentences on the website depend
on the gender of the addressed person.  An example of the use in a TT2
template:

  [% loc("{name person.name) %]

The extraction script F will expand this into two records
in the PO file, respectively with msgctxt attribute 'gender=male' and
'gender=female'.

When your PO-files are not generated by 'xgettext-perl', you do not need
a separate domain configuration file:

  $domain->configure(
    context_rules => +{gender => ['male','female']},
    translator    => $translator,
  );

When your PO-files are generated by 'xgettext-perl', you need to share
the context-rules between that msgid extractor and your runtime code. That
same file needs to be passed with the 'domain' parameter to the script.

  # add context_rules either explicit or via 'config' filename
  $domain->configure(
    config     => 'my/own/$domain.conf',
    translator => $translator,
  );

Now, when you generate the pages, you need to set-up the right context.
In this case, we set-up the gender of the person who gets addressed.
(The name 'gender' is good for examples, but quite non-descriptive.
Maybe 'user_gender' is more maintainable)

  $domain->setContext( +{gender => 'male'} );  # or ('gender=male')
  $domain->setContext( "gender=male" );        # same

=encoding utf-8

=head1 DIAGNOSTICS

=over 4

=item Fault: cannot read template from $file: $!

Cast by C

=item Warning: msgid '$msgid' contains html escapes, don't do that.  File $file line $linenr

Cast by C

=item Error: need pattern to scan for, either via new() or process()

Cast by C

=item Error: no context tags allowed in plural `$msgid'

Cast by C

=item Info: processing file $file in $charset

Cast by C

=item Info: starting new textdomain $domain, template in $filename

Cast by C

=item Error: template extract requires explicit domain

Cast by C

=item Error: template syntax error, no END in $fn line $line

Cast by C

=item Error: unknown pattern $pattern

Cast by C

=back

=head1 SEE ALSO

This module is part of Log-Report-Template version 1.04,
built on November 04, 2025. Website: F

=head1 LICENSE

For contributors see file ChangeLog.

This software is copyright (c) 2017-2025 by Mark Overmeer.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

Log-Report-Template-1.04/lib/Log/Report/Template.pm0000644000175000001440000001635315102365751022607 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.04.
# The POD got stripped from this file by OODoc version 3.05.
# For contributors see file ChangeLog.

# This software is copyright (c) 2017-2025 by Mark Overmeer.

# This is free software; you can redistribute it and/or modify it under
# the same terms as the Perl 5 programming language system itself.
# SPDX-License-Identifier: Artistic-1.0-Perl OR GPL-1.0-or-later

#oodist: *** DO NOT USE THIS VERSION FOR PRODUCTION ***
#oodist: This file contains OODoc-style documentation which will get stripped
#oodist: during its release in the distribution.  You can use this file for
#oodist: testing, however the code of this development version may be broken!

package Log::Report::Template;{
our $VERSION = '1.04';
}

use base 'Template';

use warnings;
use strict;

use Log::Report 'log-report-template';
use Log::Report::Template::Textdomain ();
# use Log::Report::Template::Extract on demand.

use File::Find        qw/find/;
use Scalar::Util      qw/blessed/;
use Template::Filters ();
use String::Print     ();


sub new
{	my $class = shift;

	# Template::Base gladly also calls _init() !!
	my $self = $class->SUPER::new(@_) or panic $class->error;
	$self;
}

sub _init($)
{	my ($self, $args) = @_;

	if(ref $self eq __PACKAGE__)
	{	# Instantiated directly
		$self->SUPER::_init($args);
	}
	else
	{	# Upgrade from existing Template object
		bless $self, __PACKAGE__;
	}

	my $delim = $self->{LRT_delim} = $args->{DELIMITER} || ':';
	my $incl = $args->{INCLUDE_PATH} || [];
	$self->{LRT_path} = ref $incl eq 'ARRAY' ? $incl : [ split $delim, $incl ];

	my $handle_errors = $args->{processing_errors} || 'NATIVE';
	if($handle_errors eq 'EXCEPTION') { $self->{LRT_exceptions} = 1 }
	elsif($handle_errors ne 'NATIVE')
	{	error __x"illegal value '{value}' for 'processing_errors' option", value => $handle_errors;
	}

	$self->{LRT_formatter} = $self->_createFormatter($args);
	$self->{LRT_trTo} = $args->{translate_to};
	$self->{LRT_tdc}  = $args->{textdomain_class} || 'Log::Report::Template::Textdomain';
	$self->_defaultFilters;
	$self;
}

sub _createFormatter($)
{	my ($self, $args) = @_;
	my $formatter = $args->{formatter};
	return $formatter if ref $formatter eq 'CODE';

	my $syntax = $args->{template_syntax} || 'HTML';
	my $modifiers = $self->_collectModifiers($args);

	my $sp     = String::Print->new(
		encode_for => ($syntax eq 'HTML' ? $syntax : undef),
		modifiers  => $modifiers,
	);

	sub { $sp->sprinti(@_) };
}

#--------------------

sub formatter() { $_[0]->{LRT_formatter} }


sub translateTo(;$)
{	my $self = shift;
	my $old  = $self->{LRT_trTo};
	@_ or return $old;

	my $lang = shift;

	return $lang   # language unchanged?
		if ! defined $lang ? ! defined $old : ! defined $old  ? 0 : $lang eq $old;

	$_->translateTo($lang) for $self->domains;
	$self->{LRT_trTo} = $lang;
}

#--------------------


sub addTextdomain($%) {
	my ($self, %args) = @_;

	if(my $only = $args{only_in_directory})
	{	my $delim = $self->{LRT_delim};
		$only     = $args{only_in_directory} = [ split $delim, $only ]
			if ref $only ne 'ARRAY';

		my @incl  = $self->_incl_path;
		foreach my $dir (@$only)
		{	next if grep $_ eq $dir, @incl;
			error __x"directory {dir} not in INCLUDE_PATH, used by {option}", dir => $dir, option => 'addTextdomain(only_in_directory)';
		}
	}

	$args{templater} ||= $self;
	$args{lang}      ||= $self->translateTo;

	my $name    = $args{name};
	my $td_class= $self->{LRT_tdc};
	my $domain;
	if($domain  = textdomain $name, 'EXISTS')
	{	$td_class->upgrade($domain, %args);
	}
	else
	{	$domain = textdomain($td_class->new(%args));
	}

	my $func    = $domain->function;
	if((my $other) = grep $func eq $_->function, $self->domains)
	{	error __x"translation function '{func}' already in use by textdomain '{name}'", func => $func, name => $other->name;
	}
	$self->{LRT_domains}{$name} = $domain;

	# call as function or as filter
	$self->_stash->{$func}  = $domain->translationFunction($self->service);
	$self->context->define_filter($func => $domain->translationFilter, 1);
	$domain;
}

sub _incl_path() { @{ $_[0]->{LRT_path}} }
sub _stash()     { $_[0]->service->context->stash }


sub domains()   { values %{$_[0]->{LRT_domains} } }


sub domain($)   { $_[0]->{LRT_domains}{$_[1]} }


sub extract(%)
{	my ($self, %args) = @_;

	eval "require Log::Report::Template::Extract";
	panic $@ if $@;

	my $stats   = $args{show_stats} || 0;
	my $charset = $args{charset}    || 'UTF-8';
	my $write   = exists $args{write_tables} ? $args{write_tables} : 1;

	my @filenames;
	if(my $fns  = $args{filenames} || $args{filename})
	{	push @filenames, ref $fns eq 'ARRAY' ? @$fns : $fns;
	}
	else
	{	my $match = $args{filename_match} || qr/\.tt2?$/;
		my $filter = sub {
			my $name = $File::Find::name;
			push @filenames, $name if -f $name && $name =~ $match;
		};
		foreach my $dir ($self->_incl_path)
		{	trace "scan $dir for template files";
			find { wanted => sub { $filter->($File::Find::name) }, no_chdir => 1}, $dir;
		}
	}

	foreach my $domain ($self->domains)
	{	my $function = $domain->function;
		my $name     = $domain->name;

		trace "extracting msgids for '$function' from domain '$name'";

		my $extr = Log::Report::Template::Extract->new(
			lexicon => $domain->lexicon,
			domain  => $name,
			pattern => "TT2-$function",
			charset => $charset,
		);

		$extr->process($_)
			for @filenames;

		$extr->showStats;
		$extr->write     if $write;
	}
}

#--------------------

sub _cols_factory(@)
{	my $self = shift;
	my $params = ref $_[-1] eq 'HASH' ? pop : undef;
	my @blocks = @_ ? @_ : 'td';
	if(@blocks==1 && $blocks[0] =~ /\$[1-9]/)
	{	my $pattern = shift @blocks;
		return sub {    # second syntax
			my @cols = split /\t/, $_[0];
			$pattern =~ s/\$([0-9]+)/$cols[$1-1] || ''/ge;
			$pattern;
		}
	}

	sub {    # first syntax
		my @cols = split /\t/, $_[0];
		my @wrap = @blocks;
		my @out;
		while(@cols)
		{	push @out, "<$wrap[0]>$cols[0]";
			shift @cols;
			shift @wrap if @wrap > 1;
		}
		join '', @out;
	}
}


sub _br_factory(@)
{	my $self = shift;
	my $params = ref $_[-1] eq 'HASH' ? pop : undef;
	return sub {
		my $templ = shift or return '';
		for($templ)
		{	s/\A[\s\n]*\n//;     # leading blank lines
			s/\n[\s\n]*\n/\n/g;  # double blank links
			s/\n[\s\n]*\z/\n/;   # trailing blank lines
			s/\s*\n/
\n/gm; # trailing blanks per line } $templ; } } sub _defaultFilters() { my $self = shift; my $context = $self->context; $context->define_filter(cols => \&_cols_factory, 1); $context->define_filter(br => \&_br_factory, 1); $self; } sub _collectModifiers($) { my ($self, $args) = @_; # First match will be used my @modifiers = @{$args->{modifiers} || []}; # More default extensions expected here. String::Print already adds a bunch. \@modifiers; } { # Log::Report exports 'error', and we use that. Our base-class # 'Template' however, also has a method named error() as well. # Gladly, they can easily be separated. # no warnings 'redefined' misbehaves, at least for perl 5.16.2 no warnings; sub error() { blessed $_[0] && $_[0]->isa('Template') or return Log::Report::error(@_); $_[0]->{LRT_exceptions} or return shift->SUPER::error(@_); @_ or panic "inexpected call to collect errors()"; # convert Template errors into Log::Report errors Log::Report::error($_[1]); } } #-------------------- 1; Log-Report-Template-1.04/lib/Log/Report/Template.pod0000644000175000001440000004641615102365751022760 0ustar00markovusers00000000000000=encoding utf8 =head1 NAME Log::Report::Template - Template Toolkit with translations =head1 INHERITANCE Log::Report::Template is a Template =head1 SYNOPSIS use Log::Report::Template; my $templater = Log::Report::Template->new(%config); $templater->addTextdomain(name => "Tic", lexicons => ...); $templater->process('template_file.tt', \%vars, \$output); =head1 DESCRIPTION This module extends Template, which is the core of Template Toolkit. The main addition is support for translations via the translation framework offered by L. You add translations to a template system, by adding calls to some translation function (by default called C) to your template text. That function will perform dark magic to collect the translation from translation tables, and fill in values. For instance: [% price = 3.14 %] EdivEPrice: [% price %]E/divE # no translation EdivE[% loc("Price: {price}") %]E/divE # translation optional It's quite a lot of work to make your templates translatable. Please read the L section before you start using this module. =head1 METHODS =head2 Constructors =over 4 =item $class-EB(%options) Create a new translator object. You may pass the C<%options> as HASH or PAIRS. By convension, all basic Template Toolkit options are in capitals. Read Template::Config about what they mean. Extension options provided by this module are all in lower-case. In a web-environment, you want to start this before your webserver starts forking. -Option --Default modifiers [] processing_errors 'NATIVE' template_syntax 'HTML' textdomain_class Log::Report::Template::Textdomain translate_to undef =over 2 =item modifiers => \@modifiers Add C<@modifiers> to the default set. Modifiers are part of the formatting process, when values get inserted in the translated string. Read L. =item processing_errors => 'NATIVE'|'EXCEPTION' The Template Toolkit infrastructure handles errors carefully: C is returned and you need to call L to collect it. =item template_syntax => 'UNKNOWN'|'HTML' Linked to L: the output of the translation is HTML encoded unless the inserted value name ends on C<_html>. Read L =item textdomain_class => CLASS Use your own extension to L. =item translate_to => LANGUAGE Globally set the output language of template processing. Usually, this is derived from the logged-in user setting or browser setting. See L. =back =back =head2 Attributes =over 4 =item $obj-EB() Get the C object which formats the messages. =item $obj-EB( [$language] ) Z<> =back =head2 Handling text domains =over 4 =item $obj-EB(%options) Create a new L object. See its C method for the options. Additional facts about the options: you may specify C as a path. Those directories must be in the INCLUDE_PATH as well. The (domain) C must be unique, and the C not yet in use. When the code also uses this textdomain, then that configuration will get extended with this configuration. » example: my $domain = $templater->addTextdomain( name => 'my-project', function => 'loc', # default ); =item $obj-EB($name) Returns the textdomain with the specified C<$name>. =item $obj-EB() Returns a LIST with all defined textdomains, unsorted. =item $obj-EB(%options) Extract message ids from the templates, and register them to the lexicon. Read section L how to use this method. Show statistics will be show when the L more is VERBOSE or DEBUG. -Option --Default charset 'UTF-8' filename_match qr/\.tt2?$/ filenames undef write_tables > =over 2 =item charset => CHARSET =item filename_match => RegEx Process all files from the INCLUDE_PATH directories which match this regular expression. =item filenames => $file|\@files By default, all filenames from the INCLUDE_PATH directories which match the C are processed, but you may explicitly create a subset by hand. =item write_tables => BOOLEAN When C, the po-files will not get updated. =back =back =head2 Template filters Some common activities in templates are harder when translation is needed. A few TT filters are provided to easy the process. =over 4 =item Filter: cols A typical example of an HTML component which needs translation is EtrEEtdEPrice:E/tdEEtdE20 £E/tdEE/trE Both the price text as value need to be translated. In plain perl (with L) you would write __x"Price: {price £}", price => $product->price # or __x"Price: {p.price £}", p => $product; In HTML, there seems to be the need for two separate translations, may in the program code. This module (actually L) can be trained to convert money during translation, because '£' is a modifier. The translation for Dutch (via a PO table) could be "Prijs: {p.price €}" SO: we want to get both table fields in one translation. Try this: EtrE[% loc("Price:\t{p.price £}" | cols %]E/trE In the translation table, you have to place the tabs (backslash-t) as well. There are two main forms of C. The first form is the containerizer: pass 'cols' a list of container names. The fields in the input string (as separated by tabs) are wrapped in the named container. The last container name will be reused for all remaining columns. By default, everything is wrapped in 'td' containers. "a\tb\tc" | cols EtdEaE/tdEEtdEbE/tdEEtdEcE/tdE "a\tb\tc" | cols('td') same "a\tb\tc" | cols('th', 'td') EthEaE/thEEtdEbE/tdEEtdEcE/tdE "a" | cols('div') EdivEaE/divE loc("a") | cols('div') EdivExxxxE/divE The second form has one pattern, which contains (at least one) C<$1> replacement positions. Missing columns for positional parameters will be left blank. "a\tb\tc" | cols('#$3#$1#') #c#a# "a" | cols('#$3#$1#') ##a# loc("a") | cols('#$3#$1#') #mies#aap# =item Filter: br Some translations will produce more than one line of text. Add 'EbrE' after each of them. [% loc('intro-text') | br %] [% | br %][% intro_text %][% END %] [% FILTER br %][% intro_text %][% END %] =back =head2 Formatter value modifiers Modifiers simplify the display of values. Read the section about modifiers in L. Here, only some examples are shown. You can achieve the same transformation with TT vmethods, or with the perl code which drives your website. The advantange is that you can translate them. And they are quite readible. =over 4 =item POSIX format C<%-10s>, C<%2.4f>, etc Exactly like format of the perl's internal C (which is actually being called to do the formatting) Examples: # pi in two decimals [% loc("π = {pi %.2f}", pi => 3.14157) %] # show int, no fraction. filesize is a template variable [% loc("file size {size %d}", size => filesize + 0.5) %] =item BYTES Convert a file size into a nice human readible format. Examples: # filesize and fn are passed as variables to the templater [% loc("downloaded {size BYTES} {fn}\n", size => fs, fn => fn) %] # may produce: " 0 B", "25 MB", "1.5 GB", etc =item Time-formatting YEAR, DATE, TIME, DT Accept various time syntaxes as value, and translate them into standard formats: year only, date in C, time as C, and various DateTime formats: Examples: # shows 'Copyright 2017' [% loc("Copyright {today YEAR}", today => '2017-06-26') %] # shows 'Created: 2017-06-26' [% loc("Created: {now DATE}", now => '2017-06-26 00:24:15') %] # shows 'Night: 00:24:15' [% loc("Night: {now TIME}", now => '2017-06-26 00:24:15') %] # shows 'Mon Jun 26 00:28:50 CEST 2017' [% loc("Stamp: {now DT(ASC)}", now => 1498429696) %] =item Default //"string", //'string', or //word When a parameter has no value or is an empty string, the word or string will take its place. [% loc("visitors: {count //0}", count => 3) %] [% loc("published: {date DT//'not yet'}", date => '') %] [% loc("copyright: {year//2017 YEAR}", year => '2018') %] [% loc("price: {price//5 EUR}", price => product.price %] [% loc("price: {price EUR//unknown}", price => 3 %] =back =head2 Template (Toolkit) base-class The details of the following functions can be found in the Template manual page. They are included here for reference only. =over 4 =item $obj-EB() If the 'processing_errors' option is 'NATIVE' (default), you have to collect the error like this: $tt->process($template_fn, $vars, ...) or die $tt->error; When the 'procesing_errors' option is set to 'EXCEPTION', the error is translated into a L: use Log::Report; try { $tt->process($template_fn, $vars, ...) }; print $@->wasFatal if $@; In the latter solution, the try() is probably only on the level of the highest level: the request handler which catches all kinds of serious errors at once. =item $obj-EB( $template, [\%vars, $output, \%options] ) Process the C<$template> into C<$output>, filling in the C<%vars>. =back =head1 DETAILS =head2 Textdomains This module uses standard gettext PO-translation tables via the L distribution. An important role here is for the 'textdomain': the name of the set of translation tables. For code, you say "use L ';" in each related module (pm file). We cannot do achieve comparible syntax with Template Toolkit: you must specify the textdomain before the templates get processed. Your website may contain multiple separate sets of templates. For instance, a standard website implementation with some local extensions. The only way to get that to work, is by using different translation functions: one textdomain may use 'loc()', where an other uses 'trans()'. =head3 Integration with Template::Toolkit Instead of Template, from Template::Toolkit, you use its extension L. # during initiation of the webserver, once in your script (before fork) my $lexicons = 'some-directory-for-translation-tables'; my $pots = Log::Report::Translator::POT->new(lexicons => $lexicons); my $templater = Log::Report::Template->new(...); my $domain = $templater->addTextdomain( name => $domainname, function => 'loc', ); $domain->configure(translator => $pots); # part of the processing per page $vars{translate_to} = 'nl_NL.utf8'; $templater->process($template, \%vars, \$output); When you use the same domain for both templates as source code, then be aware that there is only one place where you can configure the domain. This may be in the code. When you use a separate domain for the templates, then you configure as shown above. =head3 Template::Toolkit in Dancer2 When you use Dancer2, you need to connect the text domain with my $domain = (engine 'template')->addTextdomain( name => 'isaas', function => 'loc', ); And in file C: template: "TTLogReport" engines: template: TTLogReport: This "TTLogReport" refers to module L, which is part of distribution C. =head2 Supported syntax =head3 Translation syntax Let say that your translation function is called 'loc', which is the default name. Then, you can use that name as simple function. In these examples, C is a list of values to be inserted in the C string. When the C is specified with a C alternative, then a C value is required to indicate which alternative is required. [% loc("msgid", PAIRS) %] [% loc('msgid', PAIRS) %] [% loc("msgid|plural", COUNTER, PAIRS) %] [% loc("msgid|plural", _count => COUNTER, PAIRS) %] [% INCLUDE title = loc('something') %] But also as filter. Although filters and functions work differently internally in Template Toolkit, it is convenient to permit both syntaxes. [% | loc(PAIRS) %]msgid[% END %] [% 'msgid' | loc(PAIRS) %] [% "msgid" | loc(PAIRS) %] [% "msgid|plural" | loc(COUNTER, PAIRS) %] [% "msgid|plural" | loc(_count => COUNTER, PAIRS) %] [% FILTER loc %]msgid[% END %] [% FILTER loc(COUNTER, PAIRS) %]msgid|plural[% END %] As examples [% loc("hi {n}", n => name) %] [% | loc(n => name) %]hi {n}[% END %] [% "hi {n}" | loc(n => name) %] [% loc("one person|{_count} people", size) %] [% | loc(size) %]one person|{_count} people[% END %] [% 'one person|{_count} people' | loc(size) %] These syntaxes work exacly like translations with L for your Perl programs. Compare this with: __x"hi {n}", n => name; # equivalent to __x("hi {n}", n => name); # replace __x() by loc() =head3 Translation syntax, more magic With TT, we can add a simplificition which we cannot offer for Perl translations: TT variables are dynamic and stored in the stash which we can access. Therefore, we can lookup "accidentally" missed parameters. [% SET name = 'John Doe' %] [% loc("Hi {name}", name => name) %] # looks silly [% loc("Hi {name}") %] # uses TT stash directly Sometimes, computation of objects is expensive: you never know. So, you may try to avoid repeated computation. In the follow example, "soldOn" is collected/computed twice: [% IF product.soldOn %] EtdE[% loc("Sold on {product.soldOn DATE}")E/tdE [% END %] The performance is predictable optimal with: [% sold_on = product.soldOn; IF sold_on %] EtdE[% loc("Sold on {sold_on DATE}")E/tdE [% END %] =head3 Translation into HTML Usually, when data is passed from the program's internal to the template, it should get encoded into HTML to escape some characters. Typical TT code: Title: [% title | html %] When your insert is produced by the localizer, you can do this as well (set C to 'UNKNOWN' first) [% loc("Title: {t}", t => title) | html %] The default TT syntax is 'HTML', which will circumvent the need to use the html filter. In that default case, you only say: [% loc("Title: {t}", t => title) %] [% loc("Title: {title}") %] # short form, see previous section When the title is already escaped for HTML, you can circumvent that by using tags which end on 'html': [% loc("Title: {t_html}", t_html => title) %] [% SET title_html = html(title) %] [% loc("Title: {title_html}") %] =head2 Extracting PO-files You may define a textdomain without doing any translations (yet) However, when you start translating, you will need to maintain translation tables which are in PO-format. PO-files can be maintained with a wide variety of tools, for instance poedit, Pootle, virtaal, GTranslator, Lokalize, or Webtranslateit. =head3 Setting-up translations Start with desiging a domain structure. Probably, you want to create a separate domain for the templates (external texts in many languages) and your Perl program (internal texts with few languages). Pick a lexicon directory, which is also inside your version control setup, for instance your GIT repository. Some po-editors can work together with various version control systems. Now, start using this module. There are two ways: either by creating it as object, or by extension. ### As object # Somewhere in your code use Log::Report::Template; my $templater = Log::Report::Template->new(%config); $templater->addTextdomain(...); $templater->process('template_file.tt', \%vars); # runtime $templater->extract(...); # rarely, "off-line" Some way or another, you want to be able to share the creation of the templater and configuration of the textdomain between the run-time use and the irregular (off-line) extraction of msgids. The alternative is via extension: ### By extension # Somewhere in your code: use My::Template; my $templater = My::Template->new; $templater->process('template_file.tt', \%vars); # File lib/My/Template.pm package My::Template; use parent 'Log::Report::Template'; sub init($) { my ($self, $args) = @_; # add %config into %$args $self->SUPER::init($args); $self->addTextdomain(...); $self; } 1; The second solution requires a little bit of experience with OO, but is easier to maintain and to share. =head3 adding a new language The first time you run L, you will see a file being created in C<$lexicon/$textdomain-$charset.po>. That file will be left empty: copy it to start a new translation. There are many ways to structure PO-files. Which structure used, is detected automatically by L. My personal preference is C<$lexicon/$textdomain/$language-$charset.po>. On Unix-like systems, you would do: # Start a new language mkdir mylexicon/mydomain cp mylexicon/mydomain-utf8.po mylexicon/mydomain/nl_NL-utf8.po # fill the nl_NL-utf8.po file with the translation poedit mylexicon/mydomain/nl_NL-utf8.po # add the file to your version control system git add mylexicon/mydomain/nl_NL-utf8.po Now, when your program sets the locale to 'nl-NL', it should start translating to Dutch. If it doesn't, it is not always easy to figure-out what is wrong... =head3 Keeping translations up to date You have to call L when msgids have changed or added, to have the PO-tables updated. The language specific tables will get updated automatically... look for msgids which are 'fuzzy' (need update) You may also use the external program C, which is shipped with the L distribution. =head3 More performance via MO-files PO-files are quite large. You can reduce the translation table size by creating a binary "MO"-file for each of them. L will prefer mo files, if it encounters them, but generation is not (yet) organized via L components. Search for "msgfmt" as separate tool or CPAN module. =head1 DIAGNOSTICS =over 4 =item Error: directory $dir not in INCLUDE_PATH, used by $option Cast by C =item Error: illegal value '$value' for 'processing_errors' option Cast by C =item Error: translation function '$func' already in use by textdomain '$name' Cast by C =back =head1 SEE ALSO This module is part of Log-Report-Template version 1.04, built on November 04, 2025. Website: F =head1 LICENSE For contributors see file ChangeLog. This software is copyright (c) 2017-2025 by Mark Overmeer. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Log-Report-Template-1.04/README.md0000644000175000001440000000412115102365307017176 0ustar00markovusers00000000000000# distribution Log-Report-Template * My extended documentation: * Development via GitHub: * Download from CPAN: * Indexed from CPAN: This module extends "Template", which is the core of Template Toolkit. The main addition is support for translations via the translation framework offered by "Log::Report". ## Development → Release Important to know, is that I use an extension on POD to write the manuals. The "raw" unprocessed version is visible on GitHub. It will run without problems, but does not contain manual-pages. Releases to CPAN are different: "raw" documentation gets removed from the code and translated into real POD and clean HTML. This reformatting is implemented with the OODoc distribution (A name I chose before OpenOffice existed, sorry for the confusion) Clone from github for the "raw" version. For instance, when you want to contribute a new feature. On github, you can find the processed version for each release. But the better source is CPAN; to get it installed simply run: ```sh cpan -i Log::Report::Template ``` ## Contributing When you want to contribute to this module, you do not need to provide a perfect patch... actually: it is nearly impossible to create a patch which I will merge without modification. Usually, I need to adapt the style of code and documentation to my own strict rules. When you submit an extension, please contribute a set with 1. code 2. code documentation 3. regression tests in t/ **Please note:** When you contribute in any way, you agree to transfer the copyrights to Mark Overmeer (you will get the honors in the code and/or ChangeLog). You also automatically agree that your contribution is released under the same license as this project: licensed as perl itself. ## Copyright and License This project is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See Log-Report-Template-1.04/MANIFEST0000644000175000001440000000114015102365753017053 0ustar00markovusers00000000000000ChangeLog MANIFEST Makefile.PL README.md lib/Log/Report/Template.pm lib/Log/Report/Template.pod lib/Log/Report/Template/Extract.pm lib/Log/Report/Template/Extract.pod lib/Log/Report/Template/Textdomain.pm lib/Log/Report/Template/Textdomain.pod t/01use.t t/10templater.t t/12filters.t t/13modifiers.t t/14missing.t t/20examples.t t/40extract.t t/41double.t t/lexicons/first.utf-8.po t/lexicons/second.utf-8.po t/templates/root.tt xt/99pod.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Log-Report-Template-1.04/xt/0000755000175000001440000000000015102365753016361 5ustar00markovusers00000000000000Log-Report-Template-1.04/xt/99pod.t0000644000175000001440000000041215102365307017502 0ustar00markovusers00000000000000#!/usr/bin/perl use warnings; use strict; use Test::More; BEGIN { eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; plan skip_all => "devel home uses OODoc" if $ENV{MARKOV_DEVEL}; } all_pod_files_ok(); Log-Report-Template-1.04/Makefile.PL0000644000175000001440000000411215102365751017674 0ustar00markovusers00000000000000use ExtUtils::MakeMaker; use 5.016; use warnings; use strict; my $version = '1.04'; # Use command 'oodist' to produce your whole software release. my $git = "https://github.com/markov2/perl5-Log-Report-Template"; my $publish = "../public_html/log-report-template"; my $homepage = "http://perl.overmeer.net/CPAN/"; my %oodist = ( oodoc_version => 3.04, first_year => 2017, email => "markov\@cpan.org", include => [ '../Log-Report', '../Log-Report-Lexicon', '../Log-Report-Optional', '../String-Print', ], use => [ ], parser => { syntax => 'markov', skip_links => [ 'Dancer2::Config', ], pmhead => undef, }, tests => { }, release => { publish => "$publish/source", }, raw => { publish => "$publish/raw", }, generate => [ { # Add real pod to the releases format => 'pod3', podtail => undef, }, # You may add HTML formatters here. # You may add exporter configurations here. ], ); my %prereq = ( 'Scalar::Util' => 0, 'Log::Report' => 1.42, 'Log::Report::Lexicon' => 1.13, 'Template' => 2.26, 'String::Print' => 0.91, 'File::Find' => 0, ); WriteMakefile NAME => 'Log::Report::Template', VERSION => $version, PREREQ_PM => \%prereq, AUTHOR => 'Mark Overmeer ', ABSTRACT => 'template toolkit with translations', LICENSE => 'perl_5', META_MERGE => { 'meta-spec' => { version => 2 }, resources => { repository => { type => 'git', url => "$git.git", web => $git, }, homepage => $homepage, license => [ 'http//dev.perl.org/licenses/' ], }, prereqs => { develop => { requires => { 'OODoc' => '3.00', } }, test => { requires => { 'Test::More' => 1.00, 'Test::Pod' => 1.00, } }, }, # You may use multiple set-ups, see "oodist --make" x_oodist => \%oodist, }; # for translation tables #linkext:: # - PERL5LIB="lib:$PERL5LIB" bin/xgettext-perl --mode=VERBOSE -p lib/Log/Report/messages lib Log-Report-Template-1.04/ChangeLog0000644000175000001440000000320715102365307017475 0ustar00markovusers00000000000000==== version history of Log::Report::Template Unless noted otherwise, these changes where initiated and applied by Mark Overmeer. version 1.04: Tue 4 Nov 13:00:02 CET 2025 Changes: - move Dancer2 code to new Dancer2-Plugin-LogReport module. version 1.03: Mon 8 Sep 15:54:42 CEST 2025 Improvements: - normalize blanks for filtered text blocks. requested by [Andy Beverley] - convert to OODoc 3.03 version 1.02: Tue 29 Jul 09:55:57 CEST 2025 Changes: - require Perl 5.16 (2012) Fixes: - using msgids with plural alternatives. reported by [Andy Beverley] Improvements: - documentation was pretty outdated. version 1.01: Mon 2 Jun 09:51:18 CEST 2025 Fixes: - accept textdomain declaration from code and template. github issue #2, [Andy Beverley] - handle initial language setting. version 1.00: Tue 6 May 09:57:31 CEST 2025 Fixes: - fix metadata [Mohammad S Anwar] - removed extract(show_stats): they will be displayed when the Log::Report mode is DEBUG or VERBOSE. Improvements: - indentation style tab. - add gitignore - publish domains() - add Dancer2 template plugin - move Log::Report::Extract::Template from distro Log-Report-Lexicon to Log::Report::Template::Extract version 0.13: Tue Jan 23 22:26:21 CET 2018 Improvements: - convert to GIT - publish on GitHUB version 0.12: Wed 5 Jul 09:38:59 CEST 2017 Improvements: - support older perls by avoiding s///r - example with chained IF version 0.11: Thu 29 Jun 14:48:16 CEST 2017 Fixes: - dependency on Log::Report::Lexicon Improvements: - more documentation about the application version 0.10: Tue 27 Jun 16:45:08 CEST 2017 - initial release Log-Report-Template-1.04/META.yml0000644000175000001440000000244215102365753017201 0ustar00markovusers00000000000000--- abstract: 'template toolkit with translations' author: - 'Mark Overmeer ' build_requires: ExtUtils::MakeMaker: '0' Test::More: '1' Test::Pod: '1' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Log-Report-Template no_index: directory: - t - inc requires: File::Find: '0' Log::Report: '1.42' Log::Report::Lexicon: '1.13' Scalar::Util: '0' String::Print: '0.91' Template: '2.26' resources: homepage: http://perl.overmeer.net/CPAN/ repository: https://github.com/markov2/perl5-Log-Report-Template.git version: '1.04' x_oodist: email: markov@cpan.org first_year: 2017 generate: - format: pod3 podtail: ~ include: - ../Log-Report - ../Log-Report-Lexicon - ../Log-Report-Optional - ../String-Print oodoc_version: 3.04 parser: pmhead: ~ skip_links: - Dancer2::Config syntax: markov raw: publish: ../public_html/log-report-template/raw release: publish: ../public_html/log-report-template/source tests: {} use: [] x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Log-Report-Template-1.04/META.json0000644000175000001440000000450715102365753017355 0ustar00markovusers00000000000000{ "abstract" : "template toolkit with translations", "author" : [ "Mark Overmeer " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.70, CPAN::Meta::Converter version 2.150010", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Log-Report-Template", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "develop" : { "requires" : { "OODoc" : "3.00" } }, "runtime" : { "requires" : { "File::Find" : "0", "Log::Report" : "1.42", "Log::Report::Lexicon" : "1.13", "Scalar::Util" : "0", "String::Print" : "0.91", "Template" : "2.26" } }, "test" : { "requires" : { "Test::More" : "1", "Test::Pod" : "1" } } }, "release_status" : "stable", "resources" : { "homepage" : "http://perl.overmeer.net/CPAN/", "repository" : { "type" : "git", "url" : "https://github.com/markov2/perl5-Log-Report-Template.git", "web" : "https://github.com/markov2/perl5-Log-Report-Template" } }, "version" : "1.04", "x_oodist" : { "email" : "markov@cpan.org", "first_year" : 2017, "generate" : [ { "format" : "pod3", "podtail" : null } ], "include" : [ "../Log-Report", "../Log-Report-Lexicon", "../Log-Report-Optional", "../String-Print" ], "oodoc_version" : 3.04, "parser" : { "pmhead" : null, "skip_links" : [ "Dancer2::Config" ], "syntax" : "markov" }, "raw" : { "publish" : "../public_html/log-report-template/raw" }, "release" : { "publish" : "../public_html/log-report-template/source" }, "tests" : {}, "use" : [] }, "x_serialization_backend" : "JSON::PP version 4.16" }