Text::Xslate(3pm)
π Text::Xslate π
okay bestie, gather round, because this is Text::Xslate β a Scalable template engine for Perl5, and it is genuinely that girl π
(this is the NAME section, feel free to vibe with it)
π VERSION
This document describes Text::Xslate version v3.5.9. Locked in πβ¨
β¨ SYNOPSIS
here's the whole vibe, front to back:
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. she does it all, and she does it well.
So like, there are a lot of template engines in CPAN β Template-Toolkit, Text::MicroTemplate, HTML::Template, and so on β but ngl, 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. That's literally why Xslate was developed β it's the best template engine for web applications. no cap π«Ά
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 β and this is the important part β the philosophy is sandboxing: the template logic should not have no access outside the template beyond your permission. π your templates stay in their lane, fr fr.
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. it's giving speed ποΈβ¨
The template roundup project by Sam Graham shows Text::Xslate got amazingly high scores in instance_reuse condition (i.e. for persistent applications).
The template roundup project : <http://illusori.co.uk/projects/Template-Roundup/>
Perl Template Roundup October 2010 Performance vs Variant Report: instance_reuse : <http://illusori.co.uk/projects/Template-Roundup/201010/performance_vs_variant_by_feature_for_instance_reuse.html>
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. protective queen π‘οΈπ
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. iykyk π§¬
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. build whatever you want bestie π§β¨
π INTERFACE
Methods
Text::Xslate->new(%options)
Creates a new Xslate template engine with options. You can reuse this instance for multiple calls to render(). (like, don't remake it every time, that's the whole point π«Ά)
Possible options are:
path => \@path // ['.']β Specifies the include paths, which may be directory names or virtual paths, i.e. HASH references which contain$file_name => $contentpairs.
β οΈ Note that if you use taint mode (-T), you have to give absolute paths topathandcache_dir. Otherwise you'll get errors because they depend on the current working directory which might not be secure. no shortcuts here bestie π
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 uses no caches, which is provided for testing.
cache_dir => $dir // "$ENV{HOME}/.xslate_cache"β Specifies the directory used for caches. If$ENV{HOME}doesn't exist,File::Spec->tmpdirwill be used.
You should specify this option for productions to avoid conflicts of template names. (yes, in prod, please π)
function => \%functionsβ Specifies a function map which contains name-coderef pairs. A functionfmay be called asf($arg)or$arg | fin templates.
Note that these registered functions have to return a text string, not a binary string unless you want to handle bytes in whole templates. Make sure what you want to use returns either a text string or a binary string. (this trips people up CONSTANTLY π)
For example, some methods of Time::Piece might return a binary string which is encoded in UTF-8, so you'll want to decode their values.
# under LANG=ja_JP.UTF-8 on MacOSX (Darwin 11.2.0)
use Time::Piece;
use Encode qw(decode);
sub ctime {
my $ctime = Time::Piece->new->strftime; # UTF-8 encoded bytes
return decode "UTF-8", $ctime;
}
my $tx = Text::Xslate->new(
function => {
ctime => \&ctime,
},
...,
);
Built-in functions are described in Text::Xslate::Manual::Builtin.
module => [$module => ?\@import_args, ...]β Imports functions from$module, which may be a function-based or bridge module. Optional@import_argsare passed toimportas$module->import(@import_args).
For example:
# for function-based modules
my $tx = Text::Xslate->new(
module => ['Digest::SHA1' => [qw(sha1_hex)]],
);
print $tx->render_string(
'<: sha1_hex($x).substr(0, 6) :>',
{ x => foo() },
); # => 0beec7
# for bridge modules
my $tx = Text::Xslate->new(
module => ['Text::Xslate::Bridge::Star'],
);
print $tx->render_string(
'<: $x.uc() :>',
{ x => 'foo' },
); # => 'FOO'
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. it's giving flexible π
html_builder_module => [$module => ?\@import_args, ...]β Imports functions from$module, wrapping each function withhtml_builder().input_layer => $perliolayers // ':utf8'β Specifies PerlIO layers to open template files.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. (she talks a LOT at this level π£οΈ)
suffix => $ext // '.tx'β Specify the template suffix, which is used forcascadeandincludein Kolon.
Note that this is used for static name resolution. That is, the compiler uses it but the runtime engine doesn't.
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.
type => $type // 'html'β Specifies the output content type. If$typeishtmlorxml, smart escaping is applied to template expressions. That is, they are interpolated via thehtml_escapefilter. If$typeistextsmart escaping is not applied so that it is suitable for plain texts like e-mails.
$type may be html, xml (identical to html), and text.
This option is passed to the compiler directly.
line_start => $token // $parser_defined_strβ Specify the token to start line code as a string, whichquotemetawill be applied to. If you giveundef, the line code style is disabled.
This option is passed to the parser via the compiler.
tag_start => $str // $parser_defined_strβ Specify the token to start inline code as a string, whichquotemetawill be applied to.
This option is passed to the parser via the compiler.
tag_end => $str // $parser_defined_strβ Specify the token to end inline code as a string, whichquotemetawill be applied to.
This option is passed to the parser via the compiler.
header => \@template_filesβ Specify the header template files, which are inserted to the head of each template.
This option is passed to the compiler.
footer => \@template_filesβ Specify the footer template files, which are inserted to the foot of each template.
This option is passed to the compiler.
warn_handler => \&cbβ Specify the callback&cbwhich is called on warnings.die_handler => \&cbβ Specify the callback&cbwhich is called on fatal errors.pre_process_handler => \&cbβ Specify the callback&cbwhich is called after templates are loaded from the disk in order to pre-process template.
For example:
# Remove whitespace from templates
my $tx = Text::Xslate->new(
pre_process_handler => sub {
my $text = shift;
$text=~s/\s+//g;
return $text;
}
);
The first argument is the template text string, which can be both text strings and byte strings.
This filter is applied only to files, not a string template for render_string. β οΈ
$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$stringis never cached, so this method should be avoided in production environment. If you want in-memory templates, consider thepathoption 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' });
β οΈ ok important, no skipping: $string must be a text string, not a binary string. character-encoding girlies stay winning π
π $tx->load_file($file) :Void
Loads $file into memory so a later render() can use it. If it needs to, it compiles that thing and stashes it as a disk cache too. πΈ
π Text::Xslate->current_engine :XslateEngine
Hands you back the current Xslate engine while stuff is executing. If nothing's executing? You get undef, bestie. π This one is lowkey iconic when it's called from template functions and methods β that's literally its whole moment.
π Text::Xslate->current_vars :HashRef
Returns the current variable table, aka the second argument of render(), while executing. Otherwise undef. that's it, that's the vibe β¨
π Text::Xslate->current_file :Str
Returns the current file name while executing. Otherwise undef. This method is significant when it gets called by template functions and methods. π¦
π Text::Xslate->current_line :Int
Returns the current line number while executing. Otherwise undef. And yeah, same deal β it matters when template functions and methods call it. π₯
π 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. And if it sniffs out the invalid factor? It throws the exception. no chill, just facts π
π Exportable functions π
π mark_raw($str :Str) :RawStr
Marks $str as raw, so that the content of $str will be rendered as is β which means you have to escape these strings by yourself. your responsibility, bestie π
For example:
use Text::Xslate qw( mark_raw );
my $tx = Text::Xslate->new();
my $tmpl = 'Mailaddress: <: $email :>';
my %vars = (
email => mark_raw('Foo <foo at example.com>'),
);
print $tx->render_string($tmpl, \%email);
# => Mailaddress: Foo <foo@example.com>
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 it's rendered. detoxifying the raw energy β¨
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). And if $str is already a raw string? It returns $str as is. no notes, perfect behaviour π
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. glow up via wrapper β¨
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, and it's used to process directory trees or to evaluate one liners. Like, 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, and honestly that's range. π
β¨ Kolon β¨
Kolon is the default syntax, using <: ... :> inline code and : ... line code, which is explained in Text::Xslate::Syntax::Kolon. the moment, the blueprint, the original π
β¨ Metakolon β¨
Metakolon is the same as Kolon except for using [% ... %] inline code and %% ... line code, instead of <: ... :> and : .... same girl, different outfit π
β¨ TTerse β¨
TTerse is a syntax that is a subset of Template-Toolkit 2 (and partially TT3), which is explained in Text::Xslate::Syntax::TTerse.
β¨ HTMLTemplate β¨
There's HTML::Template compatible layers in CPAN. yes, in CPAN, we love that for them π
Text::Xslate::Syntax::HTMLTemplate is a syntax for HTML::Template.
HTML::Template::Parser is a converter from HTML::Template to Text::Xslate. π¦
π NOTES π
There are common notes in Xslate. listen up bestie π’
πΈ 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. silence, but make it intentional π
- to access fields β Returns nil. That is,
nil.foo.bar.bazproduces nil. - to invoke methods β Returns nil. That is,
nil.foo().bar().baz()produces nil. - to iterate β Dealt as an empty array. π«Ά
- equality β
$var == nilreturns true if and only if$varis 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 will be used. either way you're eating π
β TODO β
- Context controls. e.g.
<: [ $foo->bar @list ] :>. - Augment modifiers.
- Default arguments and named arguments for macros.
- External macros.
Just idea: in the new macro concept, macros and external templates will be the same in internals:
: macro foo($lang) { "Hello, " ~ $lang ~ " world!" }
: include foo { lang => 'Xslate' }
: # => 'Hello, Xslate world!'
: extern bar 'my/bar.tx'; # 'extern bar $file' is ok
: bar( value => 42 ); # calls an external template
: include bar { value => 42 } # ditto
- A "too-safe" HTML escaping filter which escape all the symbolic characters
π these are literally listed as TODOs in the original. manifesting them into existence fr fr β¨
π₯ 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.
the whole friend group showed up for this one ππ
πΈ 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.
aaaand that's the whole page bestie, you made it to the end π
β¨ this was Text::Xslate(3pm), generated for perl v5.42.3 on 2026-08-22 β go forth and render, icon ππ¦
π¦ where this page comes from
- ubuntu stonking: libtext-xslate-perl 3.5.9-2build2 Β· 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