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

SYNOPSIS

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

    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 multiple files
    my $tx = Text::Xslate->new();
    print $tx->render_file('hello.tx', \%vars);

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

    $tx = Text::Xslate->new(
        string => $template,
    );

    print $tx->render(\%vars);

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

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

DESCRIPTION

Text::Xslate is a template engine tuned for persistent applications. This engine introduces the virtual machine paradigm. That is, templates are compiled into xslate opcodes, and then executed by the xslate virtual machine just like as Perl does.

Note that this software is under development.

Features

High performance

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

Template cascading

Xslate supports template cascading, which allows one to extend templates with block modifiers.

This mechanism is also called as template inheritance.

INTERFACE

Methods

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

Creates a new xslate template engine.

Possible options ares:

string => $template_string

Specifies the template string, which is called <input> internally.

file => $template_file | \@template_files

Specifies file(s) to be preloaded.

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

Specifies the include paths. Default to <["."]>.

function => \%functions

Specifies functions.

Functions may be called as f($arg) or $arg | f.

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 only for testing.

input_layer => $perliolayers // ":utf8"

Specifies PerlIO layers for reading templates.

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

Renders a template with variables, and returns the result.

If $file is omitted, <input> is used. See the string option for new.

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

Exportable functions

escaped_string($str :Str) -> EscapedString

Mark $str as escaped. Escaped strings will not be escaped by the engine, so you have to escape these strings.

For example:

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

TEMPLATE SYNTAX

TODO

EXAMPLES

Variable access

    <:= $var :>
    <:= $var.field :>
    <:= $var["field"] :>
    <:= $var[0] :>

Variables may be HASH references, ARRAY references, or objects.

Loop (for)

    : for $data ->($item) {
        [<:= $item.field =>]
    : }

Iterating data may be ARRAY references.

Conditional statement (if)

    : if $var == nil {
        $var is nil.
    : }
    : else if $var != "foo" {
        $var is not nil nor "foo".
    : }
    : else {
        $var is "foo".
    : }

    : if( $var >= 1 && $var <= 10 ) {
        $var is 1 .. 10
    : }

    := $var.value == nil ? "nil" : $var.value

Expressions

Relational operators (== != < <= > >=):

    := $var == 10 ? "10"     : "not 10"
    := $var != 10 ? "not 10" : "10"

Arithmetic operators (+ - * / %):

    := $var * 10_000
    := ($var % 10) == 0

Logical operators (|| && //)

    := $var >= 0 && $var <= 10 ? "ok" : "too smaller or too larger"
    := $var // "foo" # as a default value

String operators (~)

    := "[" ~ $var ~ "]" # concatination

Operator precedence:

    (TODO)

Functions and filters

Once you have registered functions, you can call them with () or |.

    := f()        # without args
    := f(1, 2, 3) # with args
    := 42 | f     # the same as f(42)

Dynamic functions/filters:

    # code
    sub mk_indent {
        my($prefix) = @_;
        return sub {
            my($str) = @_;
            $str =~ s/^/$prefix/xmsg;
            return $str;
        }
    }
    my $tx = Text::Xslate->new(
        function => {
            indent => \&mk_indent,
        },
    );

    :# template
    := $value | indent("> ")
    := indent("> ")($value)

Template inclusion

    : include "foo.tx"

Xslate templates may be recursively included, but including depth is limited to 100.

Template cascading

You can extend templates with block modifiers.

Base templates mytmpl/base.tx:

    : block title -> { # with default
        [My Template!]
    : }

    : block body -> {;} # without default

Another derived template mytmpl/foo.tx:

    : # cascade "mytmpl/base.tx" is also okey
    : cascade mytmpl::base
    : # use default title
    : around body -> {
        My Template Body!
    : }

Yet another derived template mytmpl/bar.tx:

    : cascade mytmpl::foo
    : around title -> {
        --------------
        : super
        --------------
    : }
    : before body -> {
        Before body!
    : }
    : after body -> {
        After body!
    : }

Then, Perl code:

    my $tx = Text::Xslate->new( file => 'mytmpl/bar.tx' );
    $tx->render({});

Output:

        --------------
        [My Template!]
        --------------

        Before body!
        My Template Body!
        After Body!

This is also called as template inheritance.

Macro blocks

    : macro add ->($x, $y) {
    :=   $x + $y;
    : }
    := add(10, 20)

    : macro signeture -> {
        This is foo version <:= $VERSION :>
    : }
    := signeture()

Note that return values of macros are values that their routines renders. That is, macros themselves output nothing.

TODO

  • Template-Toolkit-like syntax

  • HTML::Template-like syntax

DEPENDENCIES

Perl 5.10.0 or later, and a C compiler.

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

Text::MicroTemplate

Text::MicroTemplate::Extended

Text::ClearSilver

Template-Toolkit

HTML::Template

HTML::Template::Pro

AUTHOR

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

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.