1Text::Xslate(3)       User Contributed Perl Documentation      Text::Xslate(3)
2
3
4

NAME

6       Text::Xslate - Scalable template engine for Perl5
7

VERSION

9       This document describes Text::Xslate version v3.5.7.
10

SYNOPSIS

12           use Text::Xslate qw(mark_raw);
13
14           my $tx = Text::Xslate->new();
15
16           my %vars = (
17               title => 'A list of books',
18               books => [
19                   { title => 'Islands in the stream' },
20                   { title => 'Programming Perl'      },
21                   # ...
22               ],
23
24               # mark HTML components as raw not to escape its HTML tags
25               gadget => mark_raw('<div class="gadget">...</div>'),
26           );
27
28           # for files
29           print $tx->render('hello.tx', \%vars);
30
31           # for strings (easy but slow)
32           my $template = q{
33               <h1><: $title :></h1>
34               <ul>
35               : for $books -> $book {
36                   <li><: $book.title :></li>
37               : } # for
38               </ul>
39           };
40
41           print $tx->render_string($template, \%vars);
42

DESCRIPTION

44       Xslate is a template engine, tuned for persistent applications, safe as
45       an HTML generator, and with rich features.
46
47       There are a lot of template engines in CPAN, for example Template-
48       Toolkit, Text::MicroTemplate, HTML::Template, and so on, but all of
49       them have some weak points: a full-featured template engine may be
50       slow, while a fast template engine may be too simple to use. This is
51       why Xslate is developed, which is the best template engine for web
52       applications.
53
54       The concept of Xslate is strongly influenced by Text::MicroTemplate and
55       Template-Toolkit 2, but the central philosophy of Xslate is different
56       from them. That is, the philosophy is sandboxing that the template
57       logic should not have no access outside the template beyond your
58       permission.
59
60       Other remarkable features are as follows:
61
62   Features
63       High performance
64
65       This engine introduces the virtual machine paradigm. Templates are
66       compiled into intermediate code, and then executed by the virtual
67       machine, which is highly optimized for rendering templates. Thus,
68       Xslate is much faster than any other template engines.
69
70       The template roundup project by Sam Graham shows Text::Xslate got
71       amazingly high scores in instance_reuse condition (i.e. for persistent
72       applications).
73
74       The template roundup project
75           <http://illusori.co.uk/projects/Template-Roundup/>
76
77       Perl Template Roundup October 2010 Performance vs Variant Report:
78       instance_reuse
79           <http://illusori.co.uk/projects/Template-Roundup/201010/performance_vs_variant_by_feature_for_instance_reuse.html>
80
81       There are also benchmarks in benchmark/ directory in the Xslate
82       distribution.
83
84       Smart escaping for HTML metacharacters
85
86       Xslate employs the smart escaping strategy, where a template engine
87       escapes all the HTML metacharacters in template expressions unless
88       users mark values as raw.  That is, the output is unlikely to prone to
89       XSS.
90
91       Template cascading
92
93       Xslate supports the template cascading, which allows you to extend
94       templates with block modifiers. It is like a traditional template
95       inclusion, but is more powerful.
96
97       This mechanism is also called as template inheritance.
98
99       Easiness to enhance
100
101       Xslate is ready to enhance. You can add functions and methods to the
102       template engine and even add a new syntax via extending the parser.
103

INTERFACE

105   Methods
106       Text::Xslate->new(%options)
107
108       Creates a new Xslate template engine with options. You can reuse this
109       instance for multiple calls to "render()".
110
111       Possible options are:
112
113       "path => \@path // ['.']"
114           Specifies the include paths, which may be directory names or
115           virtual paths, i.e. HASH references which contain "$file_name =>
116           $content" pairs.
117
118           Note that if you use taint mode ("-T"), you have to give absolute
119           paths to "path" and "cache_dir". Otherwise you'll get errors
120           because they depend on the current working directory which might
121           not be secure.
122
123       "cache => $level // 1"
124           Sets the cache level.
125
126           If "$level == 1" (default), Xslate caches compiled templates on the
127           disk, and checks the freshness of the original templates every
128           time.
129
130           If "$level >= 2", caches will be created but the freshness will not
131           be checked.
132
133           "$level == 0" uses no caches, which is provided for testing.
134
135       "cache_dir => $dir // "$ENV{HOME}/.xslate_cache""
136           Specifies the directory used for caches. If $ENV{HOME} doesn't
137           exist, "File::Spec->tmpdir" will be used.
138
139           You should specify this option for productions to avoid conflicts
140           of template names.
141
142       "function => \%functions"
143           Specifies a function map which contains name-coderef pairs.  A
144           function "f" may be called as "f($arg)" or "$arg | f" in templates.
145
146           Note that these registered functions have to return a text string,
147           not a binary string unless you want to handle bytes in whole
148           templates.  Make sure what you want to use returns either a text
149           string or a binary string.
150
151           For example, some methods of "Time::Piece" might return a binary
152           string which is encoded in UTF-8, so you'll want to decode their
153           values.
154
155               # under LANG=ja_JP.UTF-8 on MacOSX (Darwin 11.2.0)
156               use Time::Piece;
157               use Encode qw(decode);
158
159               sub ctime {
160                   my $ctime = Time::Piece->new->strftime; # UTF-8 encoded bytes
161                   return decode "UTF-8", $ctime;
162               }
163
164               my $tx = Text::Xslate->new(
165                   function => {
166                       ctime => \&ctime,
167                   },
168                   ...,
169               );
170
171           Built-in functions are described in Text::Xslate::Manual::Builtin.
172
173       "module => [$module => ?\@import_args, ...]"
174           Imports functions from $module, which may be a function-based or
175           bridge module.  Optional @import_args are passed to "import" as
176           "$module->import(@import_args)".
177
178           For example:
179
180               # for function-based modules
181               my $tx = Text::Xslate->new(
182                   module => ['Digest::SHA1' => [qw(sha1_hex)]],
183               );
184               print $tx->render_string(
185                   '<: sha1_hex($x).substr(0, 6) :>',
186                   { x => foo() },
187               ); # => 0beec7
188
189               # for bridge modules
190               my $tx = Text::Xslate->new(
191                   module => ['Text::Xslate::Bridge::Star'],
192               );
193               print $tx->render_string(
194                   '<: $x.uc() :>',
195                   { x => 'foo' },
196               ); # => 'FOO'
197
198           Because you can use function-based modules with the "module"
199           option, and also can invoke any object methods in templates, Xslate
200           doesn't require specific namespaces for plugins.
201
202       "html_builder_module => [$module => ?\@import_args, ...]"
203           Imports functions from $module, wrapping each function with
204           "html_builder()".
205
206       "input_layer => $perliolayers // ':utf8'"
207           Specifies PerlIO layers to open template files.
208
209       "verbose => $level // 1"
210           Specifies the verbose level.
211
212           If "$level == 0", all the possible errors will be ignored.
213
214           If "$level >= 1" (default), trivial errors (e.g. to print nil) will
215           be ignored, but severe errors (e.g. for a method to throw the
216           error) will be warned.
217
218           If "$level >= 2", all the possible errors will be warned.
219
220       "suffix => $ext // '.tx'"
221           Specify the template suffix, which is used for "cascade" and
222           "include" in Kolon.
223
224           Note that this is used for static name resolution. That is, the
225           compiler uses it but the runtime engine doesn't.
226
227       "syntax => $name // 'Kolon'"
228           Specifies the template syntax you want to use.
229
230           $name may be a short name (e.g. "Kolon"), or a fully qualified name
231           (e.g. "Text::Xslate::Syntax::Kolon").
232
233           This option is passed to the compiler directly.
234
235       "type => $type // 'html'"
236           Specifies the output content type. If $type is "html" or "xml",
237           smart escaping is applied to template expressions. That is, they
238           are interpolated via the "html_escape" filter.  If $type is "text"
239           smart escaping is not applied so that it is suitable for plain
240           texts like e-mails.
241
242           $type may be html, xml (identical to "html"), and text.
243
244           This option is passed to the compiler directly.
245
246       "line_start => $token // $parser_defined_str"
247           Specify the token to start line code as a string, which "quotemeta"
248           will be applied to. If you give "undef", the line code style is
249           disabled.
250
251           This option is passed to the parser via the compiler.
252
253       "tag_start => $str // $parser_defined_str"
254           Specify the token to start inline code as a string, which
255           "quotemeta" will be applied to.
256
257           This option is passed to the parser via the compiler.
258
259       "tag_end => $str // $parser_defined_str"
260           Specify the token to end inline code as a string, which "quotemeta"
261           will be applied to.
262
263           This option is passed to the parser via the compiler.
264
265       "header => \@template_files"
266           Specify the header template files, which are inserted to the head
267           of each template.
268
269           This option is passed to the compiler.
270
271       "footer => \@template_files"
272           Specify the footer template files, which are inserted to the foot
273           of each template.
274
275           This option is passed to the compiler.
276
277       "warn_handler => \&cb"
278           Specify the callback &cb which is called on warnings.
279
280       "die_handler => \&cb"
281           Specify the callback &cb which is called on fatal errors.
282
283       "pre_process_handler => \&cb"
284           Specify the callback &cb which is called after templates are loaded
285           from the disk in order to pre-process template.
286
287           For example:
288
289               # Remove whitespace from templates
290               my $tx = Text::Xslate->new(
291                   pre_process_handler => sub {
292                       my $text = shift;
293                       $text=~s/\s+//g;
294                       return $text;
295                   }
296               );
297
298           The first argument is the template text string, which can be both
299           text strings and "byte strings".
300
301           This filter is applied only to files, not a string template for
302           "render_string".
303
304       $tx->render($file, \%vars) :Str
305
306       Renders a template file with given variables, and returns the result.
307       \%vars is optional.
308
309       Note that $file may be cached according to the cache level.
310
311       $tx->render_string($string, \%vars) :Str
312
313       Renders a template string with given variables, and returns the result.
314       \%vars is optional.
315
316       Note that $string is never cached, so this method should be avoided in
317       production environment. If you want in-memory templates, consider the
318       path option for HASH references which are cached as you expect:
319
320           my %vpath = (
321               'hello.tx' => 'Hello, <: $lang :> world!',
322           );
323
324           my $tx = Text::Xslate->new( path => \%vpath );
325           print $tx->render('hello.tx', { lang => 'Xslate' });
326
327       Note that $string must be a text string, not a binary string.
328
329       $tx->load_file($file) :Void
330
331       Loads $file into memory for following "render()".  Compiles and saves
332       it as disk caches if needed.
333
334       Text::Xslate->current_engine :XslateEngine
335
336       Returns the current Xslate engine while executing. Otherwise returns
337       "undef".  This method is significant when it is called by template
338       functions and methods.
339
340       Text::Xslate->current_vars :HashRef
341
342       Returns the current variable table, namely the second argument of
343       "render()" while executing. Otherwise returns "undef".
344
345       Text::Xslate->current_file :Str
346
347       Returns the current file name while executing. Otherwise returns
348       "undef".  This method is significant when it is called by template
349       functions and methods.
350
351       Text::Xslate->current_line :Int
352
353       Returns the current line number while executing. Otherwise returns
354       "undef".  This method is significant when it is called by template
355       functions and methods.
356
357       Text::Xslate->print(...) :Void
358
359       Adds the argument into the output buffer. This method is available on
360       executing.
361
362       $tx->validate($file) :Void
363
364       Checks whether the syntax of $file is valid or invalid as Xslate.  If
365       it detects the invalid factor, this method throws the exception.
366
367   Exportable functions
368       "mark_raw($str :Str) :RawStr"
369
370       Marks $str as raw, so that the content of $str will be rendered as is,
371       so you have to escape these strings by yourself.
372
373       For example:
374
375           use Text::Xslate qw( mark_raw );
376
377           my $tx   = Text::Xslate->new();
378           my $tmpl = 'Mailaddress: <: $email :>';
379           my %vars = (
380               email => mark_raw('Foo &lt;foo at example.com&gt;'),
381           );
382           print $tx->render_string($tmpl, \%email);
383           # => Mailaddress: Foo &lt;foo@example.com&gt;
384
385       This function is available in templates as the "mark_raw" filter,
386       although the use of it is strongly discouraged.
387
388       "unmark_raw($str :Str) :Str"
389
390       Clears the raw marker from $str, so that the content of $str will be
391       escaped before rendered.
392
393       This function is available in templates as the "unmark_raw" filter.
394
395       "html_escape($str :Str) :RawStr"
396
397       Escapes HTML meta characters in $str, and returns it as a raw string
398       (see above).  If $str is already a raw string, it returns $str as is.
399
400       By default, this function will automatically be applied to all template
401       expressions.
402
403       This function is available in templates as the "html" filter, but
404       you're better off using "unmark_raw" to ensure that expressions are
405       html-escaped.
406
407       "uri_escape($str :Str) :Str"
408
409       Escapes URI unsafe characters in $str, and returns it.
410
411       This function is available in templates as the "uri" filter.
412
413       "html_builder { block } | \&function :CodeRef"
414
415       Wraps a block or &function with "mark_raw" so that the new subroutine
416       will return a raw string.
417
418       This function is used to tell the xslate engine that &function is an
419       HTML builder that returns HTML sources. For example:
420
421           sub some_html_builder {
422               my @args = @_;
423               my $html;
424               # build HTML ...
425               return $html;
426           }
427
428           my $tx = Text::Xslate->new(
429               function => {
430                   some_html_builder => html_builder(\&some_html_builder),
431               },
432           );
433
434       See also Text::Xslate::Manual::Cookbook.
435
436   Command line interface
437       The xslate(1) command is provided as a CLI to the Text::Xslate module,
438       which is used to process directory trees or to evaluate one liners.
439       For example:
440
441           $ xslate -Dname=value -o dest_path src_path
442
443           $ xslate -e 'Hello, <: $ARGV[0] :> wolrd!' Xslate
444           $ xslate -s TTerse -e 'Hello, [% ARGV.0 %] world!' TTerse
445
446       See xslate(1) for details.
447

TEMPLATE SYNTAX

449       There are multiple template syntaxes available in Xslate.
450
451       Kolon
452           Kolon is the default syntax, using "<: ... :>" inline code and ":
453           ..." line code, which is explained in Text::Xslate::Syntax::Kolon.
454
455       Metakolon
456           Metakolon is the same as Kolon except for using "[% ... %]" inline
457           code and "%% ..." line code, instead of "<: ... :>" and ": ...".
458
459       TTerse
460           TTerse is a syntax that is a subset of Template-Toolkit 2 (and
461           partially TT3), which is explained in Text::Xslate::Syntax::TTerse.
462
463       HTMLTemplate
464           There's HTML::Template compatible layers in CPAN.
465
466           Text::Xslate::Syntax::HTMLTemplate is a syntax for HTML::Template.
467
468           HTML::Template::Parser is a converter from HTML::Template to
469           Text::Xslate.
470

NOTES

472       There are common notes in Xslate.
473
474   Nil/undef handling
475       Note that nil (i.e. "undef" in Perl) handling is different from Perl's.
476       Basically it does nothing, but "verbose => 2" will produce warnings on
477       it.
478
479       to print
480           Prints nothing.
481
482       to access fields
483           Returns nil. That is, "nil.foo.bar.baz" produces nil.
484
485       to invoke methods
486           Returns nil. That is, "nil.foo().bar().baz()" produces nil.
487
488       to iterate
489           Dealt as an empty array.
490
491       equality
492           "$var == nil" returns true if and only if $var is nil.
493

DEPENDENCIES

495       Perl 5.8.1 or later.
496
497       If you have a C compiler, the XS backend will be used. Otherwise the
498       pure Perl backend will be used.
499

TODO

501       ·   Context controls. e.g. "<: [ $foo->bar @list ] :>".
502
503       ·   Augment modifiers.
504
505       ·   Default arguments and named arguments for macros.
506
507       ·   External macros.
508
509           Just idea: in the new macro concept, macros and external templates
510           will be the same in internals:
511
512               : macro foo($lang) { "Hello, " ~ $lang ~ " world!" }
513               : include foo { lang => 'Xslate' }
514               : # => 'Hello, Xslate world!'
515
516               : extern bar 'my/bar.tx';     # 'extern bar $file' is ok
517               : bar( value => 42 );         # calls an external template
518               : include bar { value => 42 } # ditto
519
520       ·   A "too-safe" HTML escaping filter which escape all the symbolic
521           characters
522

RESOURCES

524       PROJECT HOME: <https://github.com/xslate/>
525
526       REPOSITORY: <https://github.com/xslate/p5-Text-Xslate/>
527

BUGS

529       Please report issues at
530       <https://github.com/xslate/p5-Text-Xslate/issues>.  Patches are always
531       welcome.
532

SEE ALSO

534       Documents:
535
536       Text::Xslate::Manual
537
538       Xslate template syntaxes:
539
540       Text::Xslate::Syntax::Kolon
541
542       Text::Xslate::Syntax::Metakolon
543
544       Text::Xslate::Syntax::TTerse
545
546       Xslate command:
547
548       xslate
549
550       Other template modules that Xslate has been influenced by:
551
552       Text::MicroTemplate
553
554       Text::MicroTemplate::Extended
555
556       Text::ClearSilver
557
558       Template (Template::Toolkit)
559
560       HTML::Template
561
562       HTML::Template::Pro
563
564       Template::Alloy
565
566       Template::Sandbox
567
568       Benchmarks:
569
570       Template::Benchmark
571
572       Papers:
573
574       <http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf> -  Enforcing
575       Strict Model-View Separation in Template Engines
576

ACKNOWLEDGEMENT

578       Thanks to lestrrat for the suggestion to the interface of "render()",
579       the contribution of Text::Xslate::Runner (was App::Xslate), and a lot
580       of suggestions.
581
582       Thanks to tokuhirom for the ideas, feature requests, encouragement, and
583       bug finding.
584
585       Thanks to gardejo for the proposal to the name template cascading.
586
587       Thanks to makamaka for the contribution of Text::Xslate::PP.
588
589       Thanks to jjn1056 to the concept of template overlay (now implemented
590       as "cascade with ...").
591
592       Thanks to typester for the various inspirations.
593
594       Thanks to clouder for the patch of adding "AND" and "OR" to TTerse.
595
596       Thanks to punytan for the documentation improvement.
597
598       Thanks to chiba for the bug reports and patches.
599
600       Thanks to turugina for the patch to fix Win32 problems
601
602       Thanks to Sam Graham for the bug reports.
603
604       Thanks to Mons Anderson for the bug reports and patches.
605
606       Thanks to hirose31 for the feature requests and bug reports.
607
608       Thanks to c9s for the contribution of the documents.
609
610       Thanks to shiba_yu36 for the bug reports.
611
612       Thanks to kane46taka for the bug reports.
613
614       Thanks to cho45 for the bug reports.
615
616       Thanks to shmorimo for the bug reports.
617
618       Thanks to ueda for the suggestions.
619

AUTHOR

621       Fuji, Goro (gfx) <gfuji@cpan.org>.
622
623       Makamaka Hannyaharamitu (makamaka) (Text::Xslate::PP)
624
625       Maki, Daisuke (lestrrat) (Text::Xslate::Runner)
626
628       Copyright (c) 2010-2013, Fuji, Goro (gfx). All rights reserved.
629
630       This library is free software; you can redistribute it and/or modify it
631       under the same terms as Perl itself.
632
633
634
635perl v5.30.1                      2019-11-26                   Text::Xslate(3)
Impressum