The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Text::Xslate - High performance template engine

VERSION

This document describes Text::Xslate version 0.1033.

SYNOPSIS

    use Text::Xslate;
    use FindBin qw($Bin);

    my $tx = Text::Xslate->new(
        # the fillowing options are optional.
        path       => ['.'],
        cache_dir  => "$ENV{HOME}/.xslate_cache",
        cache      => 1,
    );

    my %vars = (
        title => 'A list of books',
        books => [
            { title => 'Islands in the stream' },
            { title => 'Programming Perl'      },
            { title => 'River out of Eden'     },
            { title => 'Beautiful code'        },
        ],
    );

    # for files
    print $tx->render('hello.tx', \%vars);

    # for strings
    my $template = q{
        <h1><: $title :></h1>
        <ul>
        : for $books -> $book {
            <li><: $book.title :></li>
        : } # for
        </ul>
    };

    print $tx->render_string($template, \%vars);

    # you can tell the engine that some strings are already escaped.
    use Text::Xslate qw(mark_raw);

    $vars{email} = mark_raw('gfx &lt;gfuji at cpan.org&gt;');
    # or if you don't want to pollute your namespace:
    $vars{email} = Text::Xslate::Type::Raw->new(
        'gfx &lt;gfuji at cpan.org&gt;',
    );

    # if you want Template-Toolkit syntx:
    $tx = Text::Xslate->new(syntax => 'TTerse');
    # ...

DESCRIPTION

Text::Xslate (pronounced as /eks-leit/) is a high performance template engine tuned for persistent applications. This engine introduces the virtual machine paradigm. Templates are compiled into xslate intermediate code, and then executed by the xslate virtual machine.

The concept of Xslate is strongly influenced by Text::MicroTemplate and Template-Toolkit, but the central philosophy of Xslate is different from them. That is, the philosophy is sandboxing that the template logic should not have no access outside the template beyond your permission.

This software is under development. Version 0.1xxx is a developing stage, which may include radical changes. Version 0.2xxx and more will be somewhat stable.

Features

High performance

Xslate has a virtual machine written in XS, which is highly optimized. According to benchmarks, Xslate is much faster than other template engines (Template-Toolkit, HTML::Template::Pro, Text::MicroTemplate, etc.).

There are benchmarks to compare template engines (see benchmark/ for details).

Here is a result of benchmark/others.pl to compare various template engines.

    $ perl -Mblib benchmark/others.pl include 100
    Perl/5.10.1 i686-linux
    Text::Xslate/0.1025
    Text::MicroTemplate/0.11
    Template/2.22
    Text::ClearSilver/0.10.5.4
    HTML::Template::Pro/0.94
    1..4
    ok 1 - TT: Template-Toolkit
    ok 2 - MT: Text::MicroTemplate
    ok 3 - TCS: Text::ClearSilver
    ok 4 - HT: HTML::Template::Pro
    Benchmarks with 'include' (datasize=100)
             Rate     TT     MT    TCS     HT Xslate
    TT      313/s     --   -55%   -88%   -89%   -97%
    MT      697/s   123%     --   -72%   -75%   -93%
    TCS    2512/s   702%   260%     --    -9%   -74%
    HT     2759/s   781%   296%    10%     --   -71%
    Xslate 9489/s  2931%  1261%   278%   244%     --

You can see Xslate is 3 times faster than HTML::Template::Pro and Text::ClearSilver, which are implemented in XS.

Template cascading

Xslate supports template cascading, which allows you to extend templates with block modifiers. It is like traditional template inclusion, but is more powerful.

This mechanism is also called as template inheritance.

Syntax alternation

The Xslate virtual machine and the parser/compiler are completely separated so that one can use alternative parsers.

For example, TTerse, a Template-Toolkit compatible parser, is supported as a completely different syntax parser.

INTERFACE

Methods

Text::Xslate->new(%options) :XslateEngine

Creates a new xslate template engine with options.

Possible options are:

path => \@path // ['.']

Specifies the include paths.

cache => $level // 1

Sets the cache level.

If $level == 1 (default), Xslate caches compiled templates on the disk, and checks the freshness of the original templates every time.

If $level >= 2, caches will be created but the freshness will not be checked.

$level == 0 creates no caches. It's provided for testing.

cache_dir => $dir // "$ENV{HOME}/.xslate_cache"

Specifies the directory used for caches. If $ENV{HOME} doesn't exist, File::Spec->tmpdir will be used.

You should specify this option on productions.

function => \%functions

Specifies a function map. A function f may be called as f($arg) or $arg | f.

There are a few builtin filters, but they are not overridable.

module => [$module => ?\@import_args, ...]

Imports functions from $module, which may be a function-based or bridge module. Optional @import_args are passed to import as $module->import(@import_args).

For example:

    # for function-based modules
    my $tx = Text::Xslate->new(
        module => ['Time::Piece'],
    );
    print $tx->render_string(
        '<: localtime($x).strftime() :>',
        { x => time() },
    ); # => Wed, 09 Jun 2010 10:22:06 JST

    # for bridge modules
    my $tx = Text::Xslate->new(
        module => ['SomeModule::Bridge::Xslate'],
    );
    print $tx->render_string(
        '<: $x.some_method() :>',
        { x => time() },
    );

Because you can use function-based modules with the module option, and also can invoke any object methods in templates, Xslate doesn't require specific namespaces for plugins.

input_layer => $perliolayers // ':utf8'

Specifies PerlIO layers for reading templates.

verbose => $level // 1

Specifies the verbose level.

If $level == 0, all the possible errors will be ignored.

If $level> >= 1 (default), trivial errors (e.g. to print nil) will be ignored, but severe errors (e.g. for a method to throw the error) will be warned.

If $level >= 2, all the possible errors will be warned.

suffix => $ext // '.tx'

Specify the template suffix, which is used for template cascading.

syntax => $name // 'Kolon'

Specifies the template syntax you want to use.

$name may be a short name (e.g. Kolon), or a fully qualified name (e.g. Text::Xslate::Syntax::Kolon).

This option is passed to the compiler directly.

escape => $mode // 'html'

Specifies the escape mode, which is automatically applied to template expressions.

Possible escape modes are html and none.

This option is passed to the compiler directly.

line_start => $token // $parser_defined

Specify the token to start line code, which may be a string or a regular expression.

This option is passed to the parser via the compiler.

tag_start => $str // $parser_defined

Specify the token to start inline code, which may be a string or a regular expression.

This option is passed to the parser via the compiler.

line_start => $str // $parser_defined

Specify the token to end inline code, which may be a string or a regular expression.

This option is passed to the parser via the compiler.

$tx->render($file, \%vars) :Str

Renders a template file with variables, and returns the result. \%vars is optional.

Note that $file may be cached according to the cache level.

$tx->render_string($string, \%vars) :Str

Renders a template string with variables, and returns the result. \%vars is optional.

Note that $string is never cached so that this method is suitable for testing.

$tx->load_file($file) :Void

Loads $file for following render($file, \%vars). Compiles and saves it as caches if needed.

This method can be used for pre-compiling template files.

Exportable functions

mark_raw($str :Str) -> RawString

Marks $str as raw, so that the content of $str will be rendered as is, so you have to escape these strings by yourself.

For example:

    my $tx   = Text::Xslate->new();
    my $tmpl = 'Mailaddress: <: $email :>';
    my %vars = (
        email => mark_raw('Foo &lt;foo@example.com&gt;'),
    );
    print $tx->render_string($tmpl, \%email);
    # => Mailaddress: Foo &lt;foo@example.com&gt;

This function is available in templates as the mark_raw filter:

    <: $var | mark_raw :>
    <: $var | raw # alias :>

unmark_raw($str :Str) -> Str

Clears the raw marker from $str, so that the content of $str will be escaped before rendered.

This function is available in templates as the unmark_raw filter:

    <: $var | unmark_raw :>

html_escape($str :Str) -> RawString

Escapes html special characters in $str, and returns a raw string (see above). If $str is already a raw string, it returns $str as is.

You need not call this function explicitly, because all the values will be escaped automatically.

This function is available in templates as the html filter, but keep in mind that it will do nothing if the argument is already escaped. Consider <: $var | unmark_raw | html :>, which forces to escape the argument.

Application

xslate(1) is provided as an interface to the Text::Xslate module, which is used to process directory trees or evaluate one liners. For example:

    $ xslate -D name=value -o dest_path src_path

    $ xslate -e 'Hello, <: $ARGV[0] :> wolrd!' Xslate
    $ xslate -s TTerse -e 'Hello, [% ARGV.0 %] world!' TTerse

See xslate for details.

TEMPLATE SYNTAX

There are several syntaxes you can use:

Kolon

Kolon is the default syntax, using <: ... :> tags and : ... line code, which is explained in Text::Xslate::Syntax::Kolon.

Metakolon

Metakolon is the same as Kolon except for using [% ... %] tags and %% ... line code, instead of <: ... :> and : ....

TTerse

TTerse is a syntax that is a subset of Template-Toolkit 2 (and partially TT3), which is explained in Text::Xslate::Syntax::TTerse.

NOTES

There are common notes in Xslate.

Nil/undef handling

Note that nil (i.e. undef in Perl) handling is different from Perl's. Basically it does nothing, but verbose => 2 will produce warnings on it.

to print

Prints nothing.

to access fields.

Returns nil. That is, nil.foo.bar.baz produces nil.

to invoke methods

Returns nil. That is, nil.foo().bar().baz() produces nil.

to iterate

Dealt as an empty array.

equality

$var == nil returns true if and only if $var is nil.

DEPENDENCIES

Perl 5.8.1 or later.

If you have a C compiler, the XS backend will be used. Otherwise the pure Perl backend is used.

BUGS

All complex software has bugs lurking in it, and this module is no exception. If you find a bug please either email me, or add the bug to cpan-RT. Patches are welcome :)

SEE ALSO

Xslate template syntaxes:

Text::Xslate::Syntax::Kolon

Text::Xslate::Syntax::Metakolon

Text::Xslate::Syntax::TTerse

Xslate command:

xlsate

Other template modules:

Text::MicroTemplate

Text::MicroTemplate::Extended

Text::ClearSilver

Template-Toolkit

HTML::Template

HTML::Template::Pro

Template::Alloy

Template::Sandbox

Benchmarks:

Template::Benchmark

ACKNOWLEDGEMENT

Thanks to lestrrat for the suggestion to the interface of render() and the contribution of App::Xslate.

Thanks to tokuhirom for the ideas, feature requests, encouragement, and bug finding.

Thanks to gardejo for the proposal to the name template cascading.

Thanks to jjn1056 to the concept of template overlay (now implemented as cascade with ...).

Thanks to makamaka for the contribution of Text::Xslate::PP.

AUTHOR

Fuji, Goro (gfx) <gfuji(at)cpan.org>

Makamaka Hannyaharamitu (makamaka)

Maki, Daisuke (lestrrat)

LICENSE AND COPYRIGHT

Copyright (c) 2010, Fuji, Goro (gfx). All rights reserved.

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