GithubHelp home page GithubHelp logo

template2's Introduction

Template Toolkit

Version 3.101, August 2022

Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved

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

Installation

If you have the CPAN module installed then you can install the Template Toolkit from the command line like so:

$ cpan Template

Please see the separate INSTALL file for further information on installing the Template Toolkit, including what to do if you don't have the CPAN module installed, and/or installation on MS Windows.

Description

The Template Toolkit is a collection of modules which implement a fast, flexible, powerful and extensible template processing system. It was originally designed and remains primarily useful for generating dynamic web content, but it can be used equally well for processing any other kind of text based documents: HTML, XML, POD, PostScript, LaTeX, and so on.

It can be used as a stand-alone Perl module or embedded within an Apache/mod_perl server for generating highly configurable dynamic web content. A number of Perl scripts are also provided which can greatly simplify the process of creating and managing static web content and other offline document systems.

What's New?

Version 3.101 Added meta() method to Template::Document and fixed incorrect line numbers when using outline tags

Version 3.100 Maintenance release: several fixes, documentation improvements and ttree updates.

Version 3.009 revert "Allow SET to have FILTER used in it"

Version 3.008 fixes some testing issue with CGI and taint issues.

Version 3.007 fixes a cpanm issue.

Version 3.006 adds an encoding option to Datafile plugin and refresh the contributor list and copyrights for 2020.

Version 3.004 enforced three-args open.

Version 3.003 fixes some compatibility issues with several Plugins.

Version 3.002 is a maintenance release fixing a warning during install.

Version 3.001 officially drops Perl 5.6 support.

Version 3.000 provides several performance improvements.

Version 2.29 is a maintenance release fixing a cycling weaken issue.

Version 2.28 is a maintenance release fixing some minor bugs and warnings. GitHub is now the official bug tacker tool for the project.

Version 2.27 is a maintenance release fixing some minor bugs and warnings.

Version 2.26 adds the new outline tag style and fixes various minor bugs.

Version 2.25 fixes compatibility with Perl version 5.18 and fixes a numer of other minor bugs, typos, etc.

Version 2.24 adds some new text virtual methods and fixes a silly bug in the Makefile.PL.

Version 2.23 is a maintenance release which fixes a few bugs, including one in the XS Stash which caused problems when using third party modules (e.g. DateTime) which use the string-based form of eval.

Version 2.22 is mostly a bug fixing release. The XS Stash now works with utf8 data. Tests that were failing on Win32 platforms have been fixed. Pod coverage and quality tests have been disabled except for release testing. The Autoformat plugin has been moved into a separate distribution.

Version 2.21 featured a complete clean-out of all the old HTML documentation, examples, libraries and other cruft that was way out of date and badly unloved. A new version of the HTML documentation is available for download from http://tt2.org/download/index.html#html_docs. v2.21 also fixes a memory leak in the XS Stash.

Version 2.21 also adds the STRICT option which reports the use of undefined variable values. The ANYCASE option has been improved so that you can write things like 'data.last' without the 'last' bit being interpreted as the LAST keyword. The xml filter is also new, providing a slightly more rigourous version of the html filter for use in XML documents.

Version 2.20 fixed all known bugs. It also added the Scalar and Assert plugins. The HTML documentation, examples, libraries and other bits and pieces are still provided with the distribution, but are no longer installed by the Makefile.PL. If you want them (and very few people do, it seems), then you'll need to dig them out of the distribution by yourself (or uncomment the commented-out lines in Makefile.PL that handle the installation). This has been done in an effort to simplify the installation process. All of the HTML documentation is available online at http://tt2.org/

Version 2.19 fixed some minor bugs in both Perl and XS versions of the Template Stash, and fixed a problem with a test in the test suite failing under Win32. It also added the url filter as a version of what the uri filter used to do before we fixed it to do the right thing.

Version 2.18 fixes a number of minor bugs. It also includes a modification to the parser grammar so that you can write expressions as arguments to subroutine, method or vmethod calls.

Versions 2.17 and 2.16 were interim releases by Adam Kennedy who took care of some installation problems on Mac OSX while Andy was busy elsewhere.

Version 2.15 is a major maintenance release. It applies all outstanding patches and closes all open bugs listed on http://rt.cpan.org/ It includes:

  • XS Stash: enhancements include support for tied hashes/arrays and "fallback" methods on objects (e.g. accessing hash and list items and calling virtual methods)

  • Virtual Methods: added the scalar.remove, scalar.substr, hash.delete, hash.items, hash.pairs, list.import and list.hash virtual methods. Added support for backreferences to scalar.replace and other improvements to list.push, list.unshift, list.hash, hash.list

  • Plugins: Added Math plugin, Bug fixes and enhancements to File, Image, URL and String plugins. Moved DBI, XML and GD plugins into separate distributions.

  • Numerous other bug fixes, enhancements, documentation updates, all described in detail in the Changes file.

More significant is what's not in version 2.15. The DBI plugin has been moved into a separate Template-DBI distribution, the GD plugins into Template-GD, the XML plugins into Template-XML, and the Latex filters into Template-Latex. This has been done in an effort to make the Template Toolkit core distribution smaller, cleaner and easier to configure and install.

Version 2.14 added Unicode support to TT, a full set of command line options for tpage, the 'caller' and 'callers' items to each template component, some enhancements to the XML::Simple plugin, and a number of minor bug fixes.

See the Changes file for further details of the changes in these and earlier releases.

General Features

Some of the key features of the Template Toolkit are listed below. See the documentation for further detail.

  • simple but powerful template language

  • promotes a clear separation between application functionality and presentation elements

  • variable substitution allows binding to any Perl data types (scalars, hashes, lists, subs, objects)

  • conditional blocks (IF/UNLESS/ELSIF/ELSE, SWITCH/CASE)

  • loops and iterators (FOREACH, WHILE)

  • file/template inclusion (INSERT, INCLUDE, PROCESS, WRAPPER)

  • definition of local template components (BLOCK)

  • post-processing filters (FILTER)

  • plugin module architecture for easy extensibility (USE)

  • embedded Perl can be optionally enabled (PERL/RAWPERL)

  • full exception handling (TRY/THROW/CATCH/FINAL)

  • user-defined macros (MACRO)

  • definition of template metadata (META)

  • virtual methods for complex data types (e.g. list.size, hash.keys, etc.)

  • numerous configuration options

  • modular OO architecture allows extensive customisation

  • fast LALR(1) parser modules compiles templates according to a YACC-like grammar.

  • templates compiled to Perl code for efficient runtime execution

  • in-memory and on-disk caching of compiled templates

  • simple front end module (Template.pm) for ease of use

  • numerous plugin modules: CGI, DBI, XML, URL, Date, Table, etc

  • standard filters for html, case folding, regex search and replace, etc.

Documentation

The Template Toolkit is provided with enough documentation to keep all but the most voracious reader happy for quite some time.

The 'Changes' file in the distribution directory documents all visible changes between versions of the Template Toolkit. See the section 'VERSION COMPATABILITY' below for further details.

The 'TODO' file, also in the distribution directory, lists known bugs, planned enhancements and possible new features for future versions.

The 'INSTALL' file covers the configuration and installation process.

The rest of the documentation is distributed in Pod format. The Pod pages are installed when you 'make install' and can be viewed using 'perldoc', e.g.

perldoc Template

If you're using a Unix based system then the pages should also be converted to manpages during 'make install'. Thus, you can also:

man Template

(the man pages shouldn't have any problems relating to older versions)

The documentation is also available in HTML format at the TT web site:

http://tt2.org/docs/

The documentation is now split into several sections. The 'Template' page is now much shorter, containing information relating to the specifics of using the Template module, and a brief summary of everything else. Information relating more generally to the Template Toolkit, features, syntax of the template language, plugins and so forth, has been split up into a number of Template::Manual::* pages. Template::Manual provides the index for the manual.

perldoc Template::Manual

Individual sections can be viewed as, for example,

perldoc Template::Manual::Syntax
perldoc Template::Manual::Directives
perldoc Template::Manual::Plugins

The Template::Tutorial provides an index to the tutorial documents. There are currently 2 tutorials, on generating web content, and on creating and using data files.

perldoc Template::Tutorial
perldoc Template::Tutorial::Web
perldoc Template::Tutorial::Datafile

Each of the various modules that comprise the Template Toolkit has its own associated documention. The 'Template::Modules' manpage lists these modules along with a brief description of their functions.

perldoc Template::Modules

See the individual pages for further detail:

perldoc Template::Context
perldoc Template::Parser
perldoc Template::Provider

If you're interested in the internals of the Template Toolkit and want to know more about how it all works, then you might like to have a look at the following:

perldoc Template::Manual::Internals

This document also contains important information for people wishing to hack on the Template Toolkit.

The final bit of good news is that there is now a FAQ for the Template Toolkit.

perldoc Template::FAQ

It's now got a few question in it, and better still, some answers! Further contributions welcome.

Most of the documentation is stable and reliable. Where it's not then it's usually marked as such. In particular, the documentation for the internals (Template::Manual::Internals) and FAQ (Template::FAQ) are perpetually under construction.

Source Code

The source code for the Template Toolkit is maintained in a public git repository at github:

https://github.com/abw/Template2

If you want to hack on the source code, either to fix a bug or add a feature then you should fork the repository, make the changes, commit them, and then send me a pull request. See this guide for further information.

http://help.github.com/send-pull-requests/

Any non-trivial new features should be discussed on the Template Toolkit mailing list first (see below). Don't forget to update the documentation and tests where relevant

Support

The Template Toolkit mailing list provides a forum for discussing issues relating to the use and abuse of the Template Toolkit. There are a number of knowledgeable and helpful individuals who frequent the list (including the author) who can often offer help or suggestions. Please respect their time and patience by checking the documentation and/or mailing list archives before asking questions that may already have been answered.

To subscribe to the mailing list, send an email to:

You can also use the web interface:

https://groups.io/g/template-toolkit

For information about commercial support and consultancy for the Template Toolkit, please contact the author.

Author

The Template Toolkit was written by Andy Wardley [email protected] with the invaluable assistance and contributions from many other people. See Template::Manual::Credits for details.

Copyright

Copyright (C) 1996-2022 Andy Wardley. All Rights Reserved.

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

template2's People

Contributors

2shortplanks avatar abw avatar amiri avatar andk avatar applicity avatar atoomic avatar book avatar boomfish avatar dnfm avatar dracos avatar drprofesq avatar eserte avatar f-andriot avatar grimnebulin avatar haarg avatar jacoby avatar jhannah avatar jonjensen avatar lejeunerenard avatar mremy avatar nickhibma avatar petdance avatar philiprbrenan avatar rjbs avatar sciurius avatar shlomif avatar smylers avatar spdawson avatar toddr avatar xsawyerx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

template2's Issues

The join vmethod for lists produces garbled output if its argument is utf8

Consider the following template file (call it test.tmpl):

[% a=['φοο','βαρ']; a.join('•') %]
[% a=['foo','bar']; a.join('•') %]

and the following perl script that uses the above template:

#!/usr/bin/perl
use Template;
binmode STDOUT,'utf8';
Template->new(ENCODING=>'utf8')->process('test.tmpl');

The script produces the following output:

φοο•βαρ
fooâ¢bar

As you can see, in the second line the character gets garbled while in the first line is ok. If I define my own custom list vmethod that simply calls perl's join I get the correct output, i.e.:

φοο•βαρ
foo•bar

Template::Filters - uri_filter/url_filter regex needs updating

URI::Escape now uses the RFC3986 regex as below (lines from URI::Escape)

my %Unsafe = (
RFC2732 => qr/[^A-Za-z0-9-_.!~*'()]/,
RFC3986 => qr/[^A-Za-z0-9-._~"]/
);

lines 282 and 307 in Template::Filters should be updated accordingly to match the new RFC spec. (or allow config setting of RFC version)

Or maybe it's worth just using URI::Escape instead.

This is basically copy of issue reported on cpan: https://rt.cpan.org/Public/Bug/Display.html?id=57590

Thanks!

VMethod 'defined' useless with STRICT = 1

Calling the 'defined' VMethod on an undefined variable raises the "undefined variable" error if template runtime option STRICT is on, so that VMethod is not useful then. It would be more useful if the raising of the "undefined variable" error were suppressed when the 'defined' VMethod is being processed.

Reproduction code:

use warnings;
use strict;

use Template;

my $text = '[% IF foo.defined; "Yes!"; ELSE; "No."; END %]';
my $tt = Template->new({ STRICT => 1 });
$tt->process(\$text) or die $tt->error();

This yields

var.undef error - undefined variable: foo.defined

with Template Toolkit version 2.27. I expected to get No. instead.

A workaround is to use the DEFAULT directive to assign a value to each variable that has none.

'replace' filter does not take back-references [rt.cpan.org #50212]

Migrated from rt.cpan.org#50212 (status was 'new')

Requestors:

From [email protected] on 2009-10-05 14:04:58:

Hi folks,

I have just been beating my head against the table for a while with this
problem. According to the manual for the replace method:

You can use $1, $2, etc., to reference captured parts (in parentheses) in
the regular expression.

The problem is that the 'replace' FILTER does not seem to work with these
back-references, and simply produces the literal $1, etc. Now I don't know
if this is a limit with the way the filters work or if this has simply not
yet been implemented for the filter. If this cannot work for the filter,
it would help to have a note for the 'replace' filter to specifically
state that it does not work here.

Thanks for this great module.

Mauritz Hansen

[rt.cpan.org #57464]

Migrated from rt.cpan.org#57464 (status was 'new')

Requestors:

From [email protected] on 2010-05-13 14:12:54:
If I attempt a comment block that includes other directives such as

    [%#
    <div id="menu">
        Navigation:
        <ul>
            <li><a href="[% c.uri_for('/books/list') %]">Home</a></li>
            <li><a href="[% c.uri_for('/') %]" title="Catalyst Welcome
Page">Welcome</a></li>
        </ul>
    </div><!-- end menu -->
    %]

it didn't work as the first [%# matches the %] before ">Home.

Have discussed this briefly in #catalyst and we think it's a bug not a
feature. :)

possible bug in tt 2.22 [rt.cpan.org #53688]

Migrated from rt.cpan.org#53688 (status was 'new')

Requestors:

Attachments:

From [email protected] on 2010-01-14 15:57:00:

Hello

I'm not sure it's a bug, but the behaviour changed 
from 2.15 to 2.22 and for me 2.15 was ok

I use it for processing a tt2 file
to obtain a Windows text file, I get a bad newline sequence: \r\r\n 
(I discovered it browsing the resulting attached file tpse_msgs.txt 
with an hex editor) it should be \r\n

With 2.15 everything was OK, the problem appeared after the upgrade to
2.22.
I've tried POST_CHOMP and similar but without obtaining the desired
result.

What I want to obtain is a normal newline sequence (\r\n hex 0D0A)

or go back to 2.15 :-)

best regards

Carlo Caminati


-----------------------------------------------------------------------
* Distribution name and version
    Template-Roolkit 2.22

* Perl version
	This is perl, v5.8.8 built for MSWin32-x86-multi-thread
	(with 18 registered patches, see perl -V for more detail)

	Copyright 1987-2007, Larry Wall

	Binary build 822 [280952] provided by ActiveState
http://www.ActiveState.com
	Built Jul 31 2007 19:34:48

	Perl may be copied only under the terms of either the Artistic
License or the
	GNU General Public License, which may be found in the Perl 5
source kit.

	Complete documentation for Perl, including FAQ lists, should be
found on
	this system using "man perl" or "perldoc perl".  If you have
access to the
	Internet, point your browser at http://www.perl.org/, the Perl
Home Page.

* Operating System vendor and version
      WindowsNT 1 5 x86 (Windows XP SP3)

------------------------------------------------------------------------
-----


------------------------------------------
Carlo Caminati - R&D Network Management
Selta SpA - Roveleto di Cadeo (PC) - Italy
[email protected]  -  www.selta.com
voice:+39 0523 5016200 - fax:+39 0523 5016333

test error [rt.cpan.org #69191]

Migrated from rt.cpan.org#69191 (status was 'new')

Requestors:

Attachments:

From [email protected] on 2011-06-29 22:12:45:

I'm attaching the build log, here's my perl info since this is a perlbrew build.

perl -V
                                                             hgcc
Summary of my perl5 (revision 5 version 12 subversion 4) configuration:

  Platform:
    osname=linux, osvers=2.6.39-arch, archname=i686-linux-thread-multi
    uname='linux hgcc 2.6.39-arch #1 smp preempt mon jun 27 22:01:13
cest 2011 i686 intel(r) core(tm) i3 cpu 550 @ 3.20ghz genuineintel
gnulinux '
    config_args='-de
-Dprefix=/home/ccushing/perl5/perlbrew/perls/perl-5.12.4 -Dusethreads'
    hint=recommended, useposix=true, d_sigaction=define
    useithreads=define, usemultiplicity=define
    useperlio=define, d_sfio=undef, uselargefiles=define, usesocks=undef
    use64bitint=undef, use64bitall=undef, uselongdouble=undef
    usemymalloc=n, bincompat5005=undef
  Compiler:
    cc='cc', ccflags ='-D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing
-pipe -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE
-D_FILE_OFFSET_BITS=64',
    optimize='-O2',
    cppflags='-D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe
-fstack-protector -I/usr/local/include'
    ccversion='', gccversion='4.6.1', gccosandvers=''
    intsize=4, longsize=4, ptrsize=4, doublesize=8, byteorder=1234
    d_longlong=define, longlongsize=8, d_longdbl=define, longdblsize=12
    ivtype='long', ivsize=4, nvtype='double', nvsize=8, Off_t='off_t',
lseeksize=8
    alignbytes=4, prototype=define
  Linker and Libraries:
    ld='cc', ldflags =' -fstack-protector -L/usr/local/lib'
    libpth=/usr/local/lib /lib /usr/lib
    libs=-lnsl -lgdbm -ldb -ldl -lm -lcrypt -lutil -lpthread -lc -lgdbm_compat
    perllibs=-lnsl -ldl -lm -lcrypt -lutil -lpthread -lc
    libc=/lib/libc-2.14.so, so=so, useshrplib=false, libperl=libperl.a
    gnulibc_version='2.14'
  Dynamic Linking:
    dlsrc=dl_dlopen.xs, dlext=so, d_dlsymun=undef, ccdlflags='-Wl,-E'
    cccdlflags='-fPIC', lddlflags='-shared -O2 -L/usr/local/lib
-fstack-protector'


Characteristics of this binary (from libperl):
  Compile-time options: MULTIPLICITY PERL_DONT_CREATE_GVSV
                        PERL_IMPLICIT_CONTEXT PERL_MALLOC_WRAP USE_ITHREADS
                        USE_LARGE_FILES USE_PERLIO USE_PERL_ATOF
                        USE_REENTRANT_API
  Built under linux
  Compiled at Jun 29 2011 16:04:49
  %ENV:
    PERLBREW_HOME="/home/ccushing/.perlbrew"
    PERLBREW_PATH="/home/ccushing/perl5/perlbrew/bin:/home/ccushing/perl5/perlbrew/perls/perl-5.12.4/bin"
    PERLBREW_PERL="perl-5.12.4"
    PERLBREW_ROOT="/home/ccushing/perl5/perlbrew"
    PERLBREW_VERSION="0.24"
  @INC:
    /home/ccushing/perl5/perlbrew/perls/perl-5.12.4/lib/site_perl/5.12.4/i686-linux-thread-multi
    /home/ccushing/perl5/perlbrew/perls/perl-5.12.4/lib/site_perl/5.12.4
    /home/ccushing/perl5/perlbrew/perls/perl-5.12.4/lib/5.12.4/i686-linux-thread-multi
    /home/ccushing/perl5/perlbrew/perls/perl-5.12.4/lib/5.12.4

-- 
Caleb Cushing

http://xenoterracide.com

[rt.cpan.org #73896]

Migrated from rt.cpan.org#73896 (status was 'new')

Requestors:

Attachments:

From [email protected] on 2012-01-11 13:05:20:

The attached failing test case demonstrates a problem sorting a list
that contains one hash reference.

If you uncomment the additional hash reference, the list contains two
elements and the test passes.  This problem only occurs with a one
element list.

I hope this provides enough information to diagnose the bug.

Thanks for all your great work on Template Toolkit.

Tom

Serializing a stash object?

How would I go about serializing a stash object for deferred execution?
This is probably really problematic for the *::XS variant, but for the vanilla perl version?

The use case for this would be, what if I want to have a plugin that saves the entire stash of a template's context to an object store.

Tests fail in Perl 5.18

Perl 5.18 changes the way hashes work behind the scenes. This (most likely) is causing some tests to fail.

t/vmethods/text.t ..... 1/107 FAILED 35:  - text.split.join d did not match expected

Tests fail when no '.' in @INC

[This is a ticket moved from RT #121171]

Tests fail when no '.' in @INC:

t/compile2.t: Use of uninitialized value $compiled in concatenation (.) or string at lib/Template/Provider.pm line 572. )

When no '.' is in @inc on Perl 5.25.11 or newer ( the default when executing by hand, or when PERL_USE_UNSAFE_INC=0 is set in ENV )

Tests fail as follows:

perl -Mblib=lib t/compile2.t

Use of uninitialized value $compiled in concatenation (.) or string at lib/Template/Provider.pm line 572. compiled template : Can't locate t/test/src/baz.ttc in @inc (@inc contains: ./lib ../lib lib/../blib/arch lib/../blib/lib /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11 /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11) at lib/Template/Provider.pm line 571.

1..15
ok 1
ok 2
ok 3
ok 4
ok 5 - running test_expect()
ok 6 - template processor is engaged
ok 7 - input read and split into 4 tests
Use of uninitialized value $compiled in concatenation (.) or string at lib/Template/Provider.pm line 572, chunk 1.
compiled template : Can't locate t/test/src/foo.ttc in @inc (@inc contains: ./lib ../lib lib/../blib/arch lib/../blib/lib /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11 /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11) at lib/Template/Provider.pm line 571, chunk 1.

ok 8 - template text 1 processed OK: [% INCLUDE foo a = 'any value' %...
MATCH FAILED
input: [[% INCLUDE foo a = 'any value' %]\n]
expect: [This is the hacked foo file, a is any value]
output: [This is the foo file, a is any value]
FAILED 9: - template text 1 did not match expected
not ok 9 - template text 1 did not match expected
Use of uninitialized value $compiled in concatenation (.) or string at lib/Template/Provider.pm line 572.
compiled template : Can't locate t/test/src/complex.ttc in @inc (@inc contains: ./lib ../lib lib/../blib/arch lib/../blib/lib /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11 /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11) at lib/Template/Provider.pm line 571.

ok 10 - template text 2 processed OK: [% META author => 'billg' versio...
ok 11 - template text 2 matched expected
ok 12 - template text 3 processed OK: [% META author => 'billg' versio...
ok 13 - template text 3 matched expected
Use of uninitialized value $compiled in concatenation (.) or string at lib/Template/Provider.pm line 572.
compiled template : Can't locate t/test/src/divisionbyzero.ttc in @inc (@inc contains: ./lib ../lib lib/../blib/arch lib/../blib/lib /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/site_perl/5.25.11 /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11/x86_64-linux /home/kent/perl5/perlbrew/perls/5.25.11-nossp-sip13-nopmc-nodot/lib/5.25.11) at lib/Template/Provider.pm line 571.

ok 14 - template text 4 processed OK: [%- # second pass, reads the com...
MATCH FAILED
input: [[%- # second pass, reads the compiled code from cache -%]\n[% INCLUDE divisionbyzero -%]\n]
expect: [undef error - Illegal division by zero at t/test/src/divisionbyzero line 1, chunk 1.]
output: [undef error - Illegal division by zero at t/test/src/divisionbyzero line 1.]
FAILED 15: - template text 4 did not match expected
not ok 15 - template text 4 did not match expected

Manually running the test as follows avoids the error, but it might be a runtime bug too.

kent@katipo2 ~/.cpanm/work/1492309748.22177/Template-Toolkit-2.27 $ PERL_USE_UNSAFE_INC=1 perl -Mblib=lib t/compile2.t

1..15 ok 1 ok 2 ok 3 ok 4 ok 5 - running test_expect() ok 6 - template processor is engaged ok 7 - input read and split into 4 tests ok 8 - template text 1 processed OK: [% INCLUDE foo a = 'any value' %... ok 9 - template text 1 matched expected ok 10 - template text 2 processed OK: [% META author => 'billg' versio... ok 11 - template text 2 matched expected ok 12 - template text 3 processed OK: [% META author => 'billg' versio... ok 13 - template text 3 matched expected ok 14 - template text 4 processed OK: [%- # second pass, reads the com... ok 15 - template text 4 matched expected

STRICT is not the default and does not die on error [rt.cpan.org #60959]

Migrated from rt.cpan.org#60959 (status was 'new')

Requestors:

From [email protected] on 2010-09-02 01:16:45:

I'm glad to find the STRICT option available in versions 2.21 and
above. It would be nice if it were the default. ;-) Failing that,
please document it prominently in the main synopsis, e.g.

    my $config = {
      STRICT => 1, # new since version 2.21
      ...

I would recommend that process() throw an error if the stricture checks
fail. It might be early enough to get away with that rather than
needing a NO_REALLY_STRICT_I_MEAN_IT option.

Thanks,
Eric

BUG: multi-field numerical sort [rt.cpan.org #49723]

Migrated from rt.cpan.org#49723 (status was 'new')

Requestors:
@FGasper

If I numerically sort a set of data like:

my @data = (
	{ foo: 22, bar: 128 },
	{ foo: 22, bar: 23 },
);

....in Template Toolkit using the following:

[% data.nsort('foo', 'bar') %]

....what TT will return is a sort on these strings:

22/*^UNLIKELY^*/128
22/*^UNLIKELY^*/23

....which will not match the desired behavior of numerically sorting.

To fix:

Instead of making a single sort key, have it iterate through the fields
thus when sorting:

sub list_nsort {
     my ($list, @fields) = @_;
     return $list unless @$list > 1;     # no need to sort 1 item lists
     return [
         @fields
         ?  sort { first { $a->{$_} <=> $b->{$_} } @fields }
            @$list
         :  sort { $a <=> $b }
            @$list,
     ];
}

(In fact, might this be a better way to sort alphanumerically as well?)

Check template file exists?

Hi, I have a problem that how to detect template file whether exists before render it.
In my Dancer app route service, like this:

get '/help/:subject' => { my $subject = param 'subject'; template sprintf('help/%s.tt', $subject); # will get 500 if cannot found template }

So, it could check template file exists before render it and avoid error 500. But I didnot find answer in template manual.
Any ideas? Thanks.

Errors with UTF-8 filenames with UTF-8 flag on [rt.cpan.org #67431]

Migrated from rt.cpan.org#67431 (status was 'new')

Requestors:

From [email protected] on 2011-04-13 13:48:22:

When you use UTF-8 template file names with non-ascii characters, TT  
sometimes fails with an error "file error - 1: not found".
The reason is that Perl's %INC hash always clears the UTF-8 flag on its  
keys, so when Template::Provider::_load_compiled() does delete $INC{$file}  
with $file being a UTF-8 string with flag ON, the entry is not really  
removed from %INC, and "require()" returns 1.
How to fix: add the line
  Encode::_utf8_off($file);
before
  delete $INC{$file};
My system is Debian sid with Perl 5.10.1.

How to reproduce:

#!/usr/bin/perl

use Template;
use Encode;

my $fn = 'test-��.tt';
{
     open FD, '>', $fn;
     print FD "hello world\n";
     close FD;
}
my $template = new Template({COMPILE_DIR => './', COMPILE_EXT => 'c'});
Encode::_utf8_off($fn);
$template->process($fn, {}) || die $template->error;
$template = new Template({COMPILE_DIR => './', COMPILE_EXT => 'c'});
$template->process($fn, {}) || die $template->error;
Encode::_utf8_on($fn);
$template->process($fn, {}) || die $template->error;

__END__

Here, the last process() gives the error "file error - 1: not found".

-- 
With best regards,
   VitaliyFilippov

CPAN release

Hi,

Do you plan to relates 2.27 to CPAN?

Do you need some help with maint/bugs etc. I see RT is very busy now.

Thanks.

[wishlist] Add 'preload' method to store in-memory templates

I sometimes wish I could add a precompiled template under some name for the subsequent code to rely on it. My idea of the interface is like follows:

$tt->preload( "name" => \"[% in_memory_template %]" );
# later in the code
$tt->process( "name", \%vars ); 
     # will now work on the provided template
     # instead or looking for it in INCLUDE_PATH

I managed to make a wrapper based on Template::Provider to add such feature to my particular code, but I would love to see it in Template by default.

Or maybe there's a standard way of doing this, but I haven't found it in the docs.

Would love to make a pull request for this if anybody else could need such thing.

Special treatment for Moose Objects, attention drawn to AutoBox as future delegate for VM. [rt.cpan.org #57823]

Migrated from rt.cpan.org#57823 (status was 'new')

Requestors:

From [email protected] on 2010-05-25 17:15:51:

Moose Objects should be special cased and excluded from Hash Virtual
Methods (VM)

It is the sole purpose of Moose to provide a layer of
object-introspection. The layer that TT overlays is an affront to the
smoother layer of Moose. It treats a Moose object as a Hash -- even
though one of the very purposes of Moose is to endeavor to create real
objects in Perl oblivious to their base types. I'd suggest that TT not
install VM on blessed objects, or at least not on Moose objects. I'm not
sure how much you know about Moose, or how much further I need to
continue with this. I'd be glad to give you more reasoning, but I fear
that it would all be redundant if you're already a Moose user.

VM are great for base-types, but there is a far better implementation
for Moose objects:
http://search.cpan.org/~flora/Moose-1.05/lib/Moose/Meta/Attribute/Native.pm

In fact, you could modernize TT by delegating all of this to autobox,
which does a much fuller job at abstracting base-types as objects.
http://search.cpan.org/~chocolate/autobox-2.70/lib/autobox.pod

So my priority of requests is as follows in ascending order of preference:
(a) get rid of VM on Moose
(b) get rid of VM on blessed objects
(c) delegate VM to autobox which doesn't apply to blessed types (objects).

-- 
Evan Carroll
System Lord of the Internets
http://www.evancarroll.com

Template files with mtime=0 not handled [rt.cpan.org #64142]

Migrated from rt.cpan.org#64142 (status was 'new')

Requestors:

From [email protected] on 2010-12-22 14:34:34:

Template files with mtime=0 (typically 1970-01-01 on Unix systems)
cannot be handled by Template Toolkit. This can be easily tested with
this script:

#!/usr/bin/perl

use strict;
use File::Temp qw(tempfile);
use Template;

my($tmpfh,$tmpfile) = tempfile(UNLINK => 1);
print $tmpfh "hello, world\n";
close $tmpfh or die $!;
utime 0, 0, $tmpfile or die $!;

Template->new({ABSOLUTE => 1})->process($tmpfile, {}) or die;
__END__

If the "utime" line is removed, then the script runs without problems.

Reason for this: there are a couple of places in Template::Provider,
where modtime checks are not done using "defined", but with a mere "if
(...)" or "... ||". Getting the mtime in TT2 is done using the
_template_modified method, so probably all calls of this methods should
be checked.

(If the problem is accepted, then I can provide a patch for it)

Regards,
Slaven

Documentation bug - Template::Test [rt.cpan.org #58115]

Migrated from rt.cpan.org#58115 (status was 'new')

Requestors:

From [email protected] on 2010-06-04 08:50:43:
Version 2.75 of Template Toolkit has a small bug in the documentation of
Template::Test.

The subroutines chapter shows a subroutine with the name text_expect,
while all the synopsis references a sub named test_expect. Notice the X
and S typo. One of them must certainly be wrong.

Based on the occurrence of the two different strings in the text I
assume that text_expect is the string that is wrong.

Regards,
Robin Smidsrød

[regression] Double quotes must be escaped per RFC 3986

In #13, the regexp used for RFC 3986 is incorrect and must not include double quotes. Double quotes must still be escaped, see:

http://tools.ietf.org/html/rfc3986#section-2.3
http://search.cpan.org/~gaas/URI/URI/Escape.pm

This is a severe regression as <a href="http://www.foo.com/id=[% foo FILTER uri %]&name=[% bar FILTER uri %]" would be broken if one of the variables contains a double quote in its value as it would prematurely close the URL.

TT2 doesn’t cache module loads

strace perl -MTemplate -e'Template->new()->process( \"[% USE dumper; USE dumper %]" )' 2>&1 | less

^^ The above one-liner on Linux will show that Template::Plugin::Dumper gets loaded twice. On large systems this is a significant performance problem.

replace vmethod should support braced capture variables (e.g. ${1}) [rt.cpan.org #66128]

Migrated from rt.cpan.org#66128 (status was 'new')

Requestors:

From [email protected] on 2011-02-24 16:13:21:

Currently there's no way to express something like the following with
TT2's replace vmethod:

s/(...)/${1}012/;

One could try to write

text.replace('(...)', '$1' _ '012')

but this does not work because the 2nd argument is completely
evaluated first and then passed to the replace vmethod. So the vmethod
just sees

'$1012'

as 2nd argument, which is obviously wrong.

A workaround for this problem could be the introduction of "braced"
capture variables. So one could write instead:

text.replace('(...)', '${1}' _ '012')

or even

text.replace('(...)', '${1}012')

I can provide a patch if this is accepted.

Regards,
Slaven

Template Fails When Using Windows Paths Under Cygwin

Using the Template module under Cygwin with standard Windows style paths (C:/Dir/File.tt), it bombs out with the following error:

  • file error - no providers for template prefix 'C'

This is (arguably) valid syntax and it seems that this particular scenario is not caught in Template::Context, but I will defer to you as the domain expert on what the proper fix should be. This was verified using Template v2.26 on perl 5.14, 5.20, and 5.22 across a couple variants of Windows.

Feel free to hit me up if you need a tester for verification.

TRACE_VARS using hash extraction

Simple test case:

use Template::Parser;
use Test::More;

my $template = Template::Parser
    ->new(TRACE_VARS => 1)
    ->parse('[% FOREACH [ A ] %][% B.C %][% END %]');

is_deeply $template->{VARIABLES}, {A => {B => { C => {} } } };

done_testing;

Output:

not ok 1
#   Failed test at t/auto/template/trace-vars.t line 8.
#     Structures begin differing at:
#          $got->{A}{B} = Does not exist
#     $expected->{A}{B} = HASH(0x7fdd1501b730)
1..1
# Looks like you failed 1 test of 1.

[wishlist] Support for quotemeta's \Q ... \E

Given :

[%  
    array = ['foo', 'bar', 'baz']
    v = 'ba.'
%]
[% array.grep("^$v$").size %]

I expect output 2 - and indeed it is, because $v gets interpolated into the regex, and the period is treated as a wildcard character.

Given :

[%  
    array = ['foo', 'bar', 'baz']
    v = 'ba.'
%]
[% array.grep("^\Q$v\E$").size %]

I would expect size to be 0, because literal "ba." ne "bar" - and indeed size is 0, but it would appear not because quotemeta is working, because ...

Given :

[%  
    array = ['foo', 'bar', 'baz']
    v = 'bar'
%]
[% array.grep("^\Q$v\E$").size %]

I would expect size to be 1, because literal 'bar' eq 'bar', however, Template Toolkit outputs 0.

In Perl, I would use \Q...\E as :

$ perl -we 'my $v = "ba."; print "bar" =~ /^$v$/ ? "match" : "no match";'
match


$ perl -we 'my $v = "ba."; print "bar" =~ /^\Q$v\E$/ ? "match" : "no match";'
no match

Would it be possible to add support for \Q...\E, so that I can include variables in regex whose special characters get quoted/escaped ?

"make test" fails with parallel tests enabled [rt.cpan.org #61563]

Migrated from rt.cpan.org#61563 (status was 'new')

Requestors:

From [email protected] on 2010-09-22 12:31:55:

With HARNESS_OPTIONS=-j$n and $n != 1 these will fail:

Test Summary Report
-------------------
t/compile5.t        (Wstat: 512 Tests: 3 Failed: 3)
  Failed tests:  1-3
  Non-zero exit status: 2
t/compile2.t        (Wstat: 0 Tests: 15 Failed: 2)
  Failed tests:  1-2
t/compile3.t        (Wstat: 0 Tests: 14 Failed: 2)
  Failed tests:  4-5
Files=89, Tests=2787, 11 wallclock secs ( 0.71 usr  0.56 sys + 10.18 cusr  
1.67 csys = 13.12 CPU)

Feature request: Add 'Sortkeys' option to @DUMPER_ARGS [rt.cpan.org #50678]

Migrated from rt.cpan.org#50678 (status was 'new')

Requestors:

Attachments:

From [email protected] on 2009-10-20 14:31:22:

looking at the code, Template::Plugin::Dumper currently allows the
following arguments to be passed through to Data::Dumper : Indent Pad
Varname Purity Useqq Terse Freezer Toaster Deepcopy Quotekeys Bless Maxdepth

Adding Sortkeys to this list to order hash contents consistently would
be helpful.

(also only Pad, Indent and Varname are documented in POD)

Thanks

TRIM option creates output with no newline on the final line. [rt.cpan.org #60083]

Migrated from rt.cpan.org#60083 (status was 'new')

Requestors:

Attachments:

From [email protected] on 2010-08-04 19:31:21:

The TRIM option causes output files to be written without a newline on 
the final line, which upsets software that cares about such things.  
We are generating C/C++ code from templates and g++ complains - I 
understand a C++ source with incomplete final line can cause undefined 
behaviour according to the standards.

To reproduce, please see the attached program, which runs itself 
through Template::process, and check the output.

as_list VMethod

Hello,

Almost every time when I use TT I end up adding a as_list VMethod so I can always treat a list as a list, even when it only contains a single item. To do this I use the following code:

$Template::Stash::LIST_OPS->{as_list} = sub {
    return ref($_[0]) eq 'ARRAY' ? shift : [shift];
};

It's not much really, but find myself adding it to every project I use TT for. Could it be considered to add this VMethod, or at least on that always treats a list as a list?

logs with warnings approximately 1MB/sec in size

One day, we started to see logs with warnings approximately 1MB/sec in size. Our teamlead said that he found a bug in a module and fixed it (file filters.pm)
If the solution is realy right, possibly, it makes sense to add this fix to your module?

git diff

--- a/Template/Filters.pm
+++ b/Template/Filters.pm
@@ -1,4 +1,4 @@
- #============================================================= -*-Perl-*-
+#============================================================= -*-Perl-*-
 #
 # Template::Filters
 #
@@ -25,7 +25,7 @@ use locale;
 use base 'Template::Base';
 use Template::Constants;
 use Scalar::Util 'blessed';
-
+use utf8;
 our $VERSION         = 2.87;
 our $AVAILABLE       = { };
 our $TRUNCATE_LENGTH = 32;
@@ -59,7 +59,13 @@ our $FILTERS = {
     'stderr'          => sub { print STDERR @_; return '' },
     'trim'            => sub { for ($_[0]) { s/^\s+//; s/\s+$// }; $_[0] },
     'null'            => sub { return '' },
-    'collapse'        => sub { for ($_[0]) { s/^\s+//; s/\s+$//; s/\s+/ /g };
+#'collapse' => sub { $_[0] },
+    'collapse'        => sub { for ($_[0]) {
+#s/^\s+//;
+ tr/ //s;
+#s/\s+$//;
+#s/\s+/ /g
+};
                                $_[0] },

     # dynamic filters

snippet logs with warnings

[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+442) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.
[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+440) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.
[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+41B) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.
[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+438) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.
[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+43D) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.
[Wed Jun 28 22:08:59 2017] [warn] Wide character (U+437) in substitution (s///) at /home/ubuntu/perl5/perlbrew/perls/perl-5.22.0/lib/site_perl/5.22.0/x86_64-linux/Template/Filters.pm line 62.^C

VMethods import

Documentation for import.

The import method can be called on a hash array to import the contents of another hash array.

[% hash1 = {
foo = 'Foo'
bar = 'Bar'
}
hash2 = {
wiz = 'Wiz'
woz = 'Woz'
}
%]

[% hash1.import(hash2) %]
[% hash1.wiz %] # Wiz
You can also call the import() method by itself to import a hash array into the current namespace hash.

[% user = { id => 'lwall', name => 'Larry Wall' } %]
[% import(user) %]
[% id %]: [% name %] # lwall: Larry Wall

I'm using import in two hash arrays refs;

[% data.items.import(extra.items) %]

but with that I also receiving a new array with the imported data.
so to not have something like this "ARRAY(0x7833480)" printed out in my html I also need to do:

[% myimport = data.items.import(extra.items) %]

and I think the problem is here:

in VMethods.pm

sub list_import {
my $list = shift;
push(@$list, grep defined, map ref eq 'ARRAY' ? @$_ : undef, @_);
return $list;
}

its incorrectly returning $list.

A way to show only a part of a template

We need the following feature:

Read a template file but output or process only one its block (or macros).

This can be done (with blocks but not with macroses) passing additional block argument to process() method.

A more generic way would be to pass two templates to process(): The first template would define macroses (and possibly variables), only the second template would generate output (but use blocks, variables, and macroses defined in the first template).

I propose to add both above requested features: 1. Name a block in process() method. 2. support two templates (one to set variables and blocks and another for actual output).

List VMethods (sometimes?) not called when argument is a variable [rt.cpan.org #49481]

Migrated from rt.cpan.org#49481 (status was 'new')

Requestors:

From [email protected] on 2009-09-07 10:11:43:

We have a custom vmethod called "contains". It's implemented like this:

$Template::Stash::LIST_OPS->{ contains } =
  sub {
      my ($list, $item) = @_;
      return grep($_ eq $item, @$list) ? 1 : 0;
  };

I have a constant called ITA_FIELDS, which is an arrayref of strings.

In the following testcase, contains() is never called (tested by putting
a "die" in the function):

[% SET this_var = 'a string' %]
[% constants.ITA_FIELDS.contains(this_var) %]

In the following testcase, contains() *is* called:

[% constants.ITA_FIELDS.contains('a string') %]

incorrect regexes /^foo|bar$/ instead of /^(foo|bar)$/ [rt.cpan.org #57539]

Migrated from rt.cpan.org#57539 (status was 'new')

Requestors:

From [email protected] on 2010-05-16 22:44:00:
Several places in the source code incorrectly check for regexes
of shape /^foo|bar$/ instead of /^(foo|bar)$/.
The former works, but there is a risk of matching other strings than
just "foo" and "bar", like "footage" or "carambar".

ack --nocolor --nogroup --nofilter -- "/\^\w+\|"
Context.pm:750:    if ($args[0] =~ /^on|1$/i) {
Context.pm:754:    elsif ($args[0] =~ /^off|0$/i) {
Directive.pm:653:        die \$_tt_error if \$_tt_error->type 
=~ /^return|stop\$/;
Stash.pm:78:    if ($type =~ /^scalar|item$/) {
Stash.pm:84:    elsif ($type =~ /^list|array$/) {

cannot install Template 2.24 at cygwin

I ran cpanm Template and failed

Here is the ~/.cpanm/build.log. Please note that latest cygwin has only gcc3.

make[1]: Entering directory `/home/chenbi/.cpanm/work/1341477673.5592/Template-Toolkit-2.24/xs'
gcc-4 -c    -DPERL_USE_SAFE_PUTENV -U__STRICT_ANSI__ -g3 -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include -DUSEIMPORTLIB -O3    -DVERSION=\"2.24\"  -DXS_VERSION=\"2.24\"  "-I/usr/lib/perl5/5.10/i686-cygwin/CORE"   Stash.c
/bin/sh: gcc-4: command not found
Makefile:308: recipe for target `Stash.o' failed
make[1]: *** [Stash.o] Error 127
make[1]: Leaving directory `/home/chenbi/.cpanm/work/1341477673.5592/Template-Toolkit-2.24/xs'
Makefile:900: recipe for target `subdirs' failed
make: *** [subdirs] Error 2
-> FAIL Installing . failed. See /home/chenbi/.cpanm/build.log for details.

autoformat plugin no longer found

Upgraded from 2.23 to 2.24. I have Template::Plugin::Autoformat installed.

When processing a template which uses the autoformat filter, it fails with the complaint that it cannot find the filter.

Reverting to 2.23 (leaving all other modules as they are) solves the problem.

#!/usr/bin/perl
use strict;

use Template;

my $t = <<'EOM';
<% USE autoformat %>

<% FILTER autoformat %>
Foo.
<% END %>
EOM

my $tt = Template->new({ TAG_STYLE => 'asp' });


$tt->process(\$t,{}) or die $tt->error;

The output in 2.23 is as expected:

% perl afbug

Foo.

but in 2.24 I get this:

% perl afbug
plugin error - autoformat: plugin not found

The Template::Plugin::Autoformat is unchanged between the two runs.

postfix IF strange behavior

Postfix IF statement empty variable if condition is false

{test => 5}
$test, [% test = 3 IF 0 %] $test

output:

5,  

Extend Template Toolkit with a new directive that inherits from INCLUDE directive

Hi!

I am considering to use the Template Toolkit to parse LaTeX. I would like to create a system of snippets
similar to the Perl module hierarchy of reusable code. This should help me not repeating paragraphs, sections, or chapters that are similar across several LaTeX documents.

Consider: main.tex

\documentclass[11pt,a4paper]{amsart}
\begin{document}
\title{Testing TTK}
\date{\today}
\maketitle

[[ IMPORT my/math/article/derivation1
   intro_sec='Introduction' ]]

From \eqref{eq:my:math:article:derivation1:1} it follows that ...
   
\bibliographystyle{plain}
\bibliography{myarticles}
\end{document}

and my/math/article/derivation1.tex

\section{[[ intro_sec ]]}
The equation of state is expressed in the form of the Helmholtz energy
as \cite{spa96:eqs}  
\begin{align}
  \label{eq:1}
  \frac{A(\rho, T)}{RT} = \phi(\delta, \tau) =
  \phi^o(\delta,\tau)+\phi^r(\delta, \tau)
\end{align}
where
\begin{align}
  \label{eq:2}
  \delta &= \frac{\rho}{\rho_c}\\
  \tau &= \frac{T_c}{T}.
\end{align}

So I created a new directive IMPORT that will be a superset of the INCLUDE directive. I would like the IMPORT directive to do the same as INCLUDE but also expand equation labels (and possibly more stuff). So \label{eq:1} should be converted to \label{eq:my:math:article:derivation1:1}, such that the parent document does not have to worry about conflicts in equation labels when importing a snippet.

My question is then: Is this a good idea, and is it possible to extend the Template Toolkit with new directives like IMPORT?

FILTER redirect does not honor binmode

On Windows 10, template

[% FILTER redirect("bar.txt") %]
This text is for bar.txt.
[% END %]
This text is for foo.txt.

(with DOS-style CR-LF line endings) expanded through

#! /bin/perl
use strict;
use warnings;

use Template;

my $tt = Template->new({
                        OUTPUT_PATH => '.',
                        RELATIVE => 1,
                       }) || die "$Template::ERROR\n";

my $srcfile = 'foo.txt.tt';
my $tgtfile = 'foo.txt';

open my $ofh, '>:raw', $tgtfile or die;

$tt->process($srcfile, {}, $ofh, { binmode => ':raw' })
    || die $tt->error . "\n";

creates output file foo.txt with the expected CR-LF line endings, but creates bar.txt with bad CR-CR-LF line endings:

> od -c bar.txt
0000000  \r  \r  \n   T   h   i   s       t   e   x   t       i   s
0000020   f   o   r       b   a   r   .   t   x   t   .  \r  \r  \n
0000037

The :raw stuff is needed to prevent CR-CR-LF line endings in foo.txt, too (workaround thanks to http://stackoverflow.com/questions/9123347/i-get-extra-cr-using-tt-perl-template-toolkit), but is not applied to the redirected output.
I looked at the Template source code. Template::process calls Template::Service::process to obtain the main text to output, and then calls Template::_output to output that text, taking into account the binmode passed into Template::process. Template::Service::process indirectly calls Template::_output to output the redirected text, but the binmode isn't passed into Template::Service::process so doesn't make it into Template::_output. This is inconsistent with the description at http://template-toolkit.org/docs/modules/Template.html#method_process that "binmode (...) when set to any true value will ensure that files created (but not any existing file handles passed) will be set to binary mode".
binmode specified in Template::process should be passed to any Template::_output called directly or indirectly from Template::process. I cannot quickly identify all indirect paths between Template::process and Template::_output.

Template::Manual::Plugins is missing some plugins [rt.cpan.org #63954]

Migrated from rt.cpan.org#63954 (status was 'new')

Requestors:

From [email protected] on 2010-12-15 17:19:45:

The following plugins are part of the standard TT2 installation, but not
mentioned in Template::Manual::Plugins:

  • List
  • Math
  • View

I am not sure about Template::Plugin::Procedural, as it's just used as a
base class, so probably does not need to be mentioned here.

Template::Plugin::List currently has no documentation at all, it seems.

Regards,
Slaven

Memory leak detected when ENCODING setting used

#!/usr/bin/env perl

use Template;

while (1) {
    my $template = Template->new(
        {   ABSOLUTE => 1,
            ENCODING => q{utf8},
        }
    );
    my $output;
    my $r = $template->process( '/var/www/tmpl/auth_test.html', {}, \$output );
}

1;
__END__

This process memory usage constantly increased, as you can see in process table.
But it become static, when ENCODING setting is commented.

Perl 5.18.2 x64 on CentOS 6.4 is used.

[rt.cpan.org #60640]

Migrated from rt.cpan.org#60640 (status was 'new')

Requestors:

From [email protected] on 2010-08-23 15:20:31:

TT does not save compiled on-fly templates to disk (only saves firs-
time compiled)

and second line - for help hacking via redefining functions for bases,
preprocessing,..

Provider.pm__o  Provider.pm 
--- Provider.pm__o      2010-08-20 19:33:04.000000000 +0400
+++ Provider.pm 2010-08-23 19:13:36.000000000 +0400
@@ -687,7 +687,7 @@
                 if $self->{ DEBUG };
 
             ($data, $error) = $self->_load($slot->[ NAME ], $slot->
[ DATA ]->{ name });
-            ($data, $error) = $self->_compile($data)
+            ($data, $error) = $self->_compile($data, $self->_compiled_filename($slot->[ NAME ]))
                 unless $error;
 
             if ($error) {
@@ -965,7 +965,7 @@
         local $/;
         binmode(FH);
         $data = <FH>;
-        $mod_date = (stat($path))[9];
+        $mod_date = $self->_template_modified($path);
         close(FH);
     }
     else {

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.