Log-Report-Template-1.03/0000755000175000001440000000000015057560071015724 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/0000755000175000001440000000000015057560071016472 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Log/0000755000175000001440000000000015057560071017213 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Log/Report/0000755000175000001440000000000015057560071020466 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Log/Report/Template.pod0000644000175000001440000004560615057560067022765 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 Log::Report. 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 %]
Price: [% price %]
# no translation
[% loc("Price: {price}") %]
# 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 => ARRAY Add a list of 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 Log::Report 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 => FILENAME|ARRAY 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 Price:20 £ Both the price text as value need to be translated. In plain perl (with Log::Report) 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: [% loc("Price:\t{p.price £}" | cols %] 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 abc "a\tb\tc" | cols('td') same "a\tb\tc" | cols('th', 'td') abc "a" | cols('div')
a
loc("a") | cols('div')
xxxx
The second form has one pattern, which contains (at least one) '$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 '
' 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 Log::Report::Exception: 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 Log::Report ';" 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 'L()'. =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 Log::Report 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 %] [% loc("Sold on {product.soldOn DATE}") [% END %] The performance is predictable optimal with: [% sold_on = product.soldOn; IF sold_on %] [% loc("Sold on {sold_on DATE}") [% 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 Log::Report 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 addTextdomain() =item Error: illegal value '$value' for 'processing_errors' option Cast by new() =item Error: translation function '$func' already in use by textdomain '$name' Cast by addTextdomain() =back =head1 SEE ALSO This module is part of Log-Report-Template version 1.03, built on September 08, 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.03/lib/Log/Report/Template/0000755000175000001440000000000015057560071022241 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Log/Report/Template/Textdomain.pm0000644000175000001440000001211615057560067024721 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.03. # The POD got stripped from this file by OODoc version 3.04. # 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.03'; } 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.03/lib/Log/Report/Template/Extract.pm0000644000175000001440000001136515057560067024224 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.03.
# The POD got stripped from this file by OODoc version 3.04.
# 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.03';
}

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.03/lib/Log/Report/Template/Textdomain.pod0000644000175000001440000000775515057560067025104 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

=head1 SYNOPSIS

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

=head1 DESCRIPTION

Manage one translation domain for L.

=head1 METHODS

=head2 Constructors

=over 4

=item $class-EB(%options)

Z<>

 -Option              --Default
  lang                  undef
  lexicon               undef
  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 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 Log::Report::Domain-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

=over 4

=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()

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()

The L object which is using this textdomain.

=back

=head2 Translating

=over 4

=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.

=back

=head1 DIAGNOSTICS

=over 4

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

=encoding utf-8
Cast by translationFunction()

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

Cast by upgrade()

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

Cast by translationFunction()

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

Cast by translationFunction()

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

Cast by translationFunction()

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

Cast by translationFunction()

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

Cast by translationFunction()

=back

=head1 SEE ALSO

This module is part of Log-Report-Template version 1.03,
built on September 08, 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.03/lib/Log/Report/Template/Extract.pod0000644000175000001440000002067515057560067024376 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

=head1 DIAGNOSTICS

=over 4

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

Cast by process()

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

Cast by process()

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

Cast by process()

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

Cast by store()

=item Info: processing file $file in $charset

Cast by process()

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

Cast by write()

=item Error: template extract requires explicit domain

Cast by new()

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

Cast by process()

=item Error: unknown pattern $pattern

Cast by process()

=back

=head1 SEE ALSO

This module is part of Log-Report-Template version 1.03,
built on September 08, 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.03/lib/Log/Report/Template.pm0000644000175000001440000001635415057560067022615 0ustar00markovusers00000000000000# This code is part of Perl distribution Log-Report-Template version 1.03.
# The POD got stripped from this file by OODoc version 3.04.
# 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.03';
}

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.03/lib/Dancer2/0000755000175000001440000000000015057560071017750 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Dancer2/Template/0000755000175000001440000000000015057560071021523 5ustar00markovusers00000000000000Log-Report-Template-1.03/lib/Dancer2/Template/TTLogReport.pod0000644000175000001440000001027615057560067024427 0ustar00markovusers00000000000000=encoding utf8 =head1 NAME Dancer2::Template::TTLogReport - Template toolkit engine with Log::Report translations for Dancer2 =head1 INHERITANCE Dancer2::Template::TTLogReport is a Moo::Object =head1 SYNOPSIS To use this engine, you may configure L via C: template: "TTLogReport" Or you may also change the rendering engine on a per-route basis by setting it manually with C: set template => 'TTLogReport'; Application: # In your daemon startup my $pot = Log::Report::Translator::POT->new(lexicon => $poddir); my $domain = (engine 'template')->addTextdomain(name => $mydomain); $domain->configure(translator => $pot); # Use it: get '/' => sub { template index => { title => 'my webpage', # The actual language is stored in the user session. translate_to => 'nl_NL.utf-8', }; }; =head1 DESCRIPTION This template engine allows you to use L