xslate / p5-Text-Xslate

Scalable template engine for Perl5
https://metacpan.org/release/Text-Xslate
Other
121 stars 47 forks source link
perl perl-library template xslate

Actions Status

NAME

Text::Xslate - Scalable template engine for Perl5

VERSION

This document describes Text::Xslate version v3.5.9.

SYNOPSIS

use Text::Xslate qw(mark_raw);

my $tx = Text::Xslate->new();

my %vars = (
    title => 'A list of books',
    books => [
        { title => 'Islands in the stream' },
        { title => 'Programming Perl'      },
        # ...
    ],

    # mark HTML components as raw not to escape its HTML tags
    gadget => mark_raw('<div class="gadget">...</div>'),
);

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

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

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

DESCRIPTION

Xslate is a template engine, tuned for persistent applications, safe as an HTML generator, and with rich features.

There are a lot of template engines in CPAN, for example Template-Toolkit, Text::MicroTemplate, HTML::Template, and so on, but all of them have some weak points: a full-featured template engine may be slow, while a fast template engine may be too simple to use. This is why Xslate is developed, which is the best template engine for web applications.

The concept of Xslate is strongly influenced by Text::MicroTemplate and Template-Toolkit 2, 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.

Other remarkable features are as follows:

Features

High performance

This engine introduces the virtual machine paradigm. Templates are compiled into intermediate code, and then executed by the virtual machine, which is highly optimized for rendering templates. Thus, Xslate is much faster than any other template engines.

The template roundup project by Sam Graham shows Text::Xslate got amazingly high scores in instance_reuse condition (i.e. for persistent applications).

There are also benchmarks in benchmark/ directory in the Xslate distribution.

Smart escaping for HTML metacharacters

Xslate employs the smart escaping strategy, where a template engine escapes all the HTML metacharacters in template expressions unless users mark values as raw. That is, the output is unlikely to prone to XSS.

Template cascading

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

This mechanism is also called as template inheritance.

Easiness to enhance

Xslate is ready to enhance. You can add functions and methods to the template engine and even add a new syntax via extending the parser.

INTERFACE

Methods

Text::Xslate->new(%options)

Creates a new Xslate template engine with options. You can reuse this instance for multiple calls to render().

Possible options are:

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

Renders a template file with given 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 given variables, and returns the result. \%vars is optional.

Note that $string is never cached, so this method should be avoided in production environment. If you want in-memory templates, consider the path option for HASH references which are cached as you expect:

my %vpath = (
    'hello.tx' => 'Hello, <: $lang :> world!',
);

my $tx = Text::Xslate->new( path => \%vpath );
print $tx->render('hello.tx', { lang => 'Xslate' });

Note that $string must be a text string, not a binary string.

$tx->load_file($file) :Void

Loads $file into memory for following render(). Compiles and saves it as disk caches if needed.

Text::Xslate->current_engine :XslateEngine

Returns the current Xslate engine while executing. Otherwise returns undef. This method is significant when it is called by template functions and methods.

Text::Xslate->current_vars :HashRef

Returns the current variable table, namely the second argument of render() while executing. Otherwise returns undef.

Text::Xslate->current_file :Str

Returns the current file name while executing. Otherwise returns undef. This method is significant when it is called by template functions and methods.

Text::Xslate->current_line :Int

Returns the current line number while executing. Otherwise returns undef. This method is significant when it is called by template functions and methods.

Text::Xslate->print(...) :Void

Adds the argument into the output buffer. This method is available on executing.

$tx->validate($file) :Void

Checks whether the syntax of $file is valid or invalid as Xslate. If it detects the invalid factor, this method throws the exception.

Exportable functions

mark_raw($str :Str) :RawStr

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:

use Text::Xslate qw( mark_raw );

my $tx   = Text::Xslate->new();
my $tmpl = 'Mailaddress: <: $email :>';
my %vars = (
    email => mark_raw('Foo &lt;foo at 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, although the use of it is strongly discouraged.

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.

html_escape($str :Str) :RawStr

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

By default, this function will automatically be applied to all template expressions.

This function is available in templates as the html filter, but you're better off using unmark_raw to ensure that expressions are html-escaped.

uri_escape($str :Str) :Str

Escapes URI unsafe characters in $str, and returns it.

This function is available in templates as the uri filter.

html_builder { block } | \&function :CodeRef

Wraps a block or &function with mark_raw so that the new subroutine will return a raw string.

This function is used to tell the xslate engine that &function is an HTML builder that returns HTML sources. For example:

sub some_html_builder {
    my @args = @_;
    my $html;
    # build HTML ...
    return $html;
}

my $tx = Text::Xslate->new(
    function => {
        some_html_builder => html_builder(\&some_html_builder),
    },
);

See also Text::Xslate::Manual::Cookbook.

Command line interface

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

$ xslate -Dname=value -o dest_path src_path

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

See xslate(1) for details.

TEMPLATE SYNTAX

There are multiple template syntaxes available in Xslate.

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.

DEPENDENCIES

Perl 5.8.1 or later.

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

TODO

RESOURCES

PROJECT HOME: https://github.com/xslate/

REPOSITORY: https://github.com/xslate/p5-Text-Xslate/

BUGS

Please report issues at https://github.com/xslate/p5-Text-Xslate/issues. Patches are always welcome.

SEE ALSO

Documents:

Text::Xslate::Manual

Xslate template syntaxes:

Text::Xslate::Syntax::Kolon

Text::Xslate::Syntax::Metakolon

Text::Xslate::Syntax::TTerse

Xslate command:

xslate

Other template modules that Xslate has been influenced by:

Text::MicroTemplate

Text::MicroTemplate::Extended

Text::ClearSilver

Template (Template::Toolkit)

HTML::Template

HTML::Template::Pro

Template::Alloy

Template::Sandbox

Benchmarks:

Template::Benchmark

Papers:

http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf - Enforcing Strict Model-View Separation in Template Engines

ACKNOWLEDGEMENT

Thanks to lestrrat for the suggestion to the interface of render(), the contribution of Text::Xslate::Runner (was App::Xslate), and a lot of suggestions.

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 makamaka for the contribution of Text::Xslate::PP.

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

Thanks to typester for the various inspirations.

Thanks to clouder for the patch of adding AND and OR to TTerse.

Thanks to punytan for the documentation improvement.

Thanks to chiba for the bug reports and patches.

Thanks to turugina for the patch to fix Win32 problems

Thanks to Sam Graham for the bug reports.

Thanks to Mons Anderson for the bug reports and patches.

Thanks to hirose31 for the feature requests and bug reports.

Thanks to c9s for the contribution of the documents.

Thanks to shiba_yu36 for the bug reports.

Thanks to kane46taka for the bug reports.

Thanks to cho45 for the bug reports.

Thanks to shmorimo for the bug reports.

Thanks to ueda for the suggestions.

AUTHOR

Fuji, Goro (gfx) gfuji@cpan.org.

Makamaka Hannyaharamitu (makamaka) (Text::Xslate::PP)

Maki, Daisuke (lestrrat) (Text::Xslate::Runner)

LICENSE AND COPYRIGHT

Copyright (c) 2010-2013, 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.