Log::R...emplate(3pm)
π NAME π
Log::Report::Template β Template Toolkit, but make it translatable π
π¦ INHERITANCE π¦
Log::Report::Template
is a Template
β¨ SYNOPSIS β¨
use Log::Report::Template;
my $templater = Log::Report::Template->new(%config);
$templater->addTextdomain(name => "Tic", lexicons => ...);
$templater->process('template_file.tt', \%vars, \$output);
πΈ DESCRIPTION πΈ
Okay so bestie, this module is a glow-up on Template, which is literally the beating heart of Template Toolkit π. The one big main-character addition? Translations. It hooks into the translation framework that Log::Report gives you.
Here's the vibe: you make your template system bilingual by sprinkling calls to a translation function into your template text (by default that function is called loc()), and then that function does dark magic β¨ to go fetch the right translation out of the translation tables and fill in the values. Like so:
[% price = 3.14 %]
<div>Price: [% price %]</div> # no translation
<div>[% loc("Price: {price}") %]</div> # translation optional
ngl making your templates translatable is a lot of work. So before you just start yeeting loc() everywhere, please read the "DETAILS" section first, okay? π
π METHODS π
π Constructors π
$class->new(%options)
Spawn a brand-new translator object β¨. You can pass the %options as a HASH or as PAIRS. By convension (yes that's the word, iykyk), every basic Template Toolkit option is in CAPITALS β go read Template::Config if you wanna know what those mean. The extension options that this module adds are all in lower-case.
In a web-environment, you wanna start this before your webserver starts forking. Like, before. π
-Option --Default
modifiers []
processing_errors 'NATIVE'
template_syntax 'HTML'
textdomain_class Log::Report::Template::Textdomain
translate_to undef
modifiers => \@modifiersβ chucks@modifiersinto the default set. Modifiers are part of the formatting process, specifically the part where values get slotted into the translated string. Go read "Formatter value modifiers" πprocessing_errors => 'NATIVE'|'EXCEPTION'β the Template Toolkit infrastructure is so careful with errors bestie:undefgets returned, and you have to callerror()to go collect it π«Άtemplate_syntax => 'UNKNOWN'|'HTML'β tied toString::Print::new(encode_for): the translation output gets HTML encoded unless the inserted value's name ends on_html. Go read "Translation into HTML" πtextdomain_class => CLASSβ use your own extension ofLog::Report::Template::Textdomainif you're feeling fancy β¨translate_to => LANGUAGEβ sets the output language of template processing globally. Normally this comes from the logged-in user setting or the browser setting. SeetranslateTo(). π
π§ Attributes π§
$obj->formatter()β grabs you theString::Printobject, the one that formats the messages π$obj->translateTo( [$language] )
π Handling text domains π
$obj->addTextdomain(%options)β creates a fresh newLog::Report::Template::Textdomainobject π. Check itsnew()method for what options it takes.
Extra deets about those options: you can give "only_in_directory" as a path, and those directories must be in the INCLUDE_PATH too, no exceptions. The (domain) "name" has to be unique, and the "function" must not already be in use.
And when the code also uses this textdomain, then that configuration gets extended with this configuration. Two-for-one π«Ά
Β» example:
my $domain = $templater->addTextdomain(
name => 'my-project',
function => 'loc', # default
);
$obj->domain($name)β hands you back the textdomain with that$nameπ«$obj->domains()β gives you a LIST of every defined textdomain. Unsorted, bestie, we don't sort here π$obj->extract(%options)β extracts message ids out of the templates and registers them to the lexicon. Read the "Extracting PO-files" section to find out how to actually use this method π
Show statistics will be show when the Log::Report mode is VERBOSE or DEBUG β¨
-Option --Default
charset 'UTF-8'
filename_match qr/\.tt2?$/
filenames undef
write_tables <C<true>>
charset => CHARSETfilename_match => RegExβ processes every file from the INCLUDE_PATH directories that matches this regular expression πfilenames => $file|\@filesβ by default, every filename from the INCLUDE_PATH directories matchingfilename_matchgets processed, but you can explicitly hand-build a subset if you want πwrite_tables => BOOLEANβ whenfalse, the po-files do not get updated. Bestie, be careful. π«£
π Template filters π
Some pretty common activities in templates get harder once translation enters the chat π. So a few TT filters are provided to make that process easier.
Filter: cols
A classic example of an HTML component that needs translation:
<tr><td>Price:</td><td>20 Β£</td></tr>
Both the price text and the value need translating. In plain perl (with Log::Report) you'd write:
__x"Price: {price Β£}", price => $product->price # or
__x"Price: {p.price Β£}", p => $product;
But in HTML, there seems to be a need for two separate translations, may in the program code. This module (actually String::Print) 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:
<tr>[% loc("Price:\t{p.price Β£}" | cols %]</tr>
In the translation table, you have to place the tabs (backslash-t) as well. No skipping, bestie β οΈ
There are two main forms of "cols". The first form is the containerizer: pass 'cols' a list of container names, and the fields in the input string (separated by tabs, obvi) get wrapped in the named container. The last container name will be reused for all the remaining columns. By default, everything gets wrapped in 'td' containers π
"a\tb\tc" | cols <td>a</td><td>b</td><td>c</td>
"a\tb\tc" | cols('td') same
"a\tb\tc" | cols('th', 'td') <th>a</th><td>b</td><td>c</td>
"a" | cols('div') <div>a</div>
loc("a") | cols('div') <div>xxxx</div>
The second form has one pattern, and that pattern contains (at least one) $1 replacement positions β¨. Any missing columns for positional parameters get left blank.
"a\tb\tc" | cols('#$3#$1#') #c#a#
"a" | cols('#$3#$1#') ##a#
loc("a") | cols('#$3#$1#') #mies#aap#
Filter: br
Some translations are gonna produce more than one line of text. This one slaps a '<br>' after each of them π
[% loc('intro-text') | br %]
[% | br %][% intro_text %][% END %]
[% FILTER br %][% intro_text %][% END %]
π Formatter value modifiers π
Modifiers make displaying values way easier. Go read the section about modifiers in String::Print for the full tea β here we're only showing some examples π
You can pull off the same transformation with TT vmethods, or with the perl code driving your website. The advantange is that you can translate them. And they're quite readible. Slay.
POSIX format "%-10s", "%2.4f", etc
Exactly like the format of perl's internal printf() (which is actually what gets called to do the formatting, no cap) π₯
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) %]
BYTES
Converts 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
Time-formatting YEAR, DATE, TIME, DT
Takes various time syntaxes as the value and translates them into standard formats: year only, date in "YYYY-MM-DD", time as "HH::MM::SS", 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) %]
Default //"string", //'string', or //word
When a parameter has no value, or is an empty string, the word or string takes 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 %]
β Template (Toolkit) base-class β
The deets of the following functions live in the Template manual page. They're included here for reference only, bestie π
$obj->error()β if the'processing_errors'option is'NATIVE'(the default), you have to go collect the error like this:
$tt->process($template_fn, $vars, ...)
or die $tt->error;
When the 'processing_errors' option is set to 'EXCEPTION', the error gets translated into a Log::Report::Exception:
use Log::Report;
try { $tt->process($template_fn, $vars, ...) };
print $@->wasFatal if $@;
In that latter solution, the try() is probably only at the level of the highest level: the request handler, which catches all kinds of serious errors at once π₯
$obj->process( $template, [\%vars, $output, \%options] )β processes the$templateinto$output, filling in the%varsβ¨
π DETAILS π
Textdomains
okay so here's the tea β this module runs on standard gettext PO-translation tables, served up via the Log::Report::Lexicon distribution. And the main character of this whole situation? The 'textdomain' β which is literally just the name of a set of translation tables. that's it. that's the role. π
For code, you say use Log::Report '<textdomain>; inside every related module (pm file). We cannot do achieve comparible syntax with Template Toolkit: you must specify the textdomain before the templates get processed. no takebacksies.
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()'. two functions, two vibes, no overlap π
Integration with Template::Toolkit
Instead of Template, from Template::Toolkit, you use its extension Log::Report::Template. slay β¨
# 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. one configuration spot, bestie, choose it wisely π
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 "config.ini":
template: "TTLogReport"
engines:
template:
TTLogReport:
This "TTLogReport" refers to module Dancer2::Template::TTLogReport, which is part of distribution "Log-Report". iykyk π¦
Supported syntax
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. iconic default behavior fr fr.
In these examples, "PAIRS" is a list of values to be inserted in the "msgid" string. When the "msgid" is specified with a "plural" alternative, then a "COUNTER" 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. (yes, both. we contain multitudes π )
[% | 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()
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 %]
E<lt>tdE<gt>[% loc("Sold on {product.soldOn DATE}")E<lt>/tdE<gt>
[% END %]
The performance is predictable optimal with:
[% sold_on = product.soldOn; IF sold_on %]
E<lt>tdE<gt>[% loc("Sold on {sold_on DATE}")E<lt>/tdE<gt>
[% END %]
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 "template_syntax" 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}") %]
Extracting PO-files
You may define a textdomain without doing any translations (yet) β no pressure bestie π«Ά 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.
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. π
adding a new language
The first time you run extract(), you will see a file being created in "$lexicon/$textdomain-$charset.po". That file will be left empty: copy it to start a new translation. (empty file, fresh start, main character energy π)
There are many ways to structure PO-files. Which structure used, is detected automatically by Log::Report::Lexicon. My personal preference is "$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... π mood.
Keeping translations up to date
You have to call extract() 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 "xgettext-perl", which is shipped with the Log::Report::Lexicon distribution.
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. Log::Report::Lexicon 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. π₯
π¨ DIAGNOSTICS π¨
- Error: directory $dir not in INCLUDE_PATH, used by $option β Cast by
addTextdomain() - Error: illegal value '$value' for 'processing_errors' option β Cast by
new() - Error: translation function '$func' already in use by textdomain '$name' β Cast by
addTextdomain()
π¦ SEE ALSO π¦
This module is part of Log-Report-Template version 1.04, built on November 04, 2025. Website: http://perl.overmeer.net/CPAN/ β¨
π 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. π«Ά
and that's the whole page bestie, no notes π
the footer said this was perl v5.40.1, dated 2026-01-24, for Log::Report::Template(3pm) β literally iconic, go forth and translate ππ
π¦ where this page comes from
- ubuntu resolute: liblog-report-template-perl 1.04-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: liblog-report-template-perl 1.04-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms