1Text::Xslate::Syntax::KUosleorn(C3o)ntributed Perl DocumTeenxtta:t:iXosnlate::Syntax::Kolon(3)
2
3
4

NAME

6       Text::Xslate::Syntax::Kolon - The default template syntax
7

SYNOPSIS

9           use Text::Xslate;
10           my $tx = Text::Xslate->new(
11               syntax => 'Kolon', # optional
12           );
13
14           print $tx->render_string(
15               'Hello, <: $dialect :> world!',
16               { dialect => 'Kolon' }
17           );
18

DESCRIPTION

20       Kolon is the default syntax, using "<: ... :>" tags and ": ..." line
21       code. In this syntax all the features in Xslate are available.
22

SYNTAX

24   Variable access
25       Variable access:
26
27           <: $var :>
28
29       Field access:
30
31           <: $var.0 :>
32           <: $var.field :>
33           <: $var.accessor :>
34
35           <: $var["field"] :>
36           <: $var[0] :>
37
38       Variables may be HASH references, ARRAY references, or objects.
39       Because "$var.field" and $var["field"] are the same semantics,
40       $obj["accessor"] syntax may be call object methods.
41
42   Literals
43       Special:
44
45           : nil   # as undef, indicating "nothing"
46           : true  # as the integer 1
47           : false # as the integer 0
48
49       String:
50
51           : "foo\n" # the same as perl
52           : 'foo\n' # the same as perl
53
54       Number:
55
56           : 42
57           : 3.14
58           : 0xFF   # hex
59           : 0777   # octal
60           : 0b1010 # binary
61
62       Array:
63
64           : for [1, 2, 3] -> $i { ... }
65
66       Hash:
67
68           : foo({ foo => "bar" })
69
70       Note that "{ ... }" is always parsed as hash literals, so you don't
71       need to use the <+> prefix as Perl sometimes requires:
72
73           :  {}.kv(); # ok
74           : +{}.kv(); # also ok
75
76   Expressions
77       Conditional operator ("?:"):
78
79           : $var.value == nil ? "nil" : $var.value
80
81       Relational operators ("== != < <= > >="):
82
83           : $var == 10 ? "10"     : "not 10"
84           : $var != 10 ? "not 10" : "10"
85
86       Note that "==" and "!=" are similar to Perl's "eq" and "ne" except that
87       "$var == nil" is true iff $var is uninitialized, while other relational
88       operators are numerical.
89
90       Arithmetic operators ("+ - * / % min max"):
91
92           : $var * 10_000
93           : ($var % 10) == 0
94           : 10 min 20 min 30 # 10
95           : 10 max 20 max 30 # 30
96
97       Bitwise operators ("prefix:<+^> +& +| +^")
98
99           : 0x1010 +| 0x3200 # bitwise or:  0x3210
100           : 0x1010 +& 0x3200 # bitwise and: 0x1000
101           : 0x1010 +^ 0x3200 # bitwise xor: 0x0210
102           : +^0x1010         # bitwise neg: 0xFFFFEFEF (on 32 bit system)
103
104       Logical operators ("! && || // not and or")
105
106           : $var >= 0 && $var <= 10 ? "ok" : "too smaller or too larger"
107           : $var // "foo" # as a default value
108
109       String operators ("~")
110
111           : "[" ~ $var ~ "]" # concatenation
112
113       The operator precedence is very like Perl's:
114
115           . () []
116           prefix:<!> prefix:<+> prefix:<-> prefix:<+^>
117           * / % x +&
118           + - ~ +| +^
119           prefix:<defined>
120           < <= > >=
121           == !=
122           |
123           &&
124           || // min max
125           ?:
126           not
127           and
128           or
129
130   Constants (or binding)
131       You can define lexical constants with "constant", which requires a bare
132       word, and "my", which requires a variable name.
133
134           : constant FOO = 42;
135           : my      $foo = 42;
136
137       These two statements has the same semantics, so you cannot modify $foo.
138
139           : my $foo = 42; $foo = 3.14; # compile error!
140
141   Loops
142       There are "for" loops that are like Perl's "foreach".
143
144           : # iterate over an ARRAY reference
145           : for $data -> $item {
146               [<: $item.field :>]
147           : }
148
149           : # iterate over a HASH reference
150           : # You must specify how to iterate it (.keys(), .values() or .kv())
151           : for $data.keys() -> $key {
152               <: $key :>=<: $data[$key] :>
153           : }
154
155       And the "for" statement can take an "else" block:
156
157           : for $data -> $item {
158               [<: $item.field :>]
159           : }
160           : else {
161               Nothing in data
162           : }
163
164       The "else" block is executed if $data is an empty array or nil.
165
166       You can get the iterator index in "for" statements as "$~ITERATOR_VAR":
167
168           : for $data -> $item {
169               : if ($~item % 2) == 0 {
170                   Even (0, 2, 4, ...)
171               : }
172               : else {
173                   Odd (1, 3, 5, ...)
174               : }
175           : }
176
177       "$~ITERATOR_VAR" is a pseudo object, so you can access its elements via
178       the dot-name syntax.
179
180           : for $data -> $i {
181               : $~i       # 0-origin iterator index (0, 1, 2, ...)
182               : $~i.index # the same as $~i
183               : $~i.count # the same as $~i + 1
184
185               : if ($~i.index % 2) == 0 {
186                   even
187               : }
188               : else {
189                   odd
190               : }
191               : $~i.cycle("even", "odd") # => "even" -> "odd" -> "even" -> "odd" ...
192           : }
193
194       Supported iterator elements are "index :Int", "count :Int", "body :
195       ArrayRef", "size : Int", "max_index :Int", "is_first :Bool", "is_last
196       :Bool", "peek_next :Any", "peek_prev :Any", "cycle(...) :Any".
197
198       "while" loops are also supported in the same semantics as Perl's:
199
200           : # $obj might be an iteratable object
201           : while $dbh.fetch() -> $item {
202               [<: $item.field :>]
203           : }
204
205       "while defined expr -> $item" is interpreted as "while defined(my $item
206       = expr)" for convenience.
207
208           : while defined $dbh.fetch() -> $item {
209               [<: $item # $item can be false-but-defined :>]
210           : }
211
212       Loop control statements, namely "next" and "last", are also supported
213       in both "for" and "while" loops.
214
215           : for $data -> $item {
216               : last if $item == 42
217               ...
218           : }
219
220   Conditional statements
221       There are "if-else" and "given-when" conditional statements.
222
223       "if-else":
224
225           : if $var == nil {
226               $var is nil.
227           : }
228           : else if $var != "foo" { # elsif is okay
229               $var is not nil nor "foo".
230           : }
231           : else {
232               $var is "foo".
233           : }
234
235           : if( $var >= 1 && $var <= 10 ) {
236               $var is 1 .. 10
237           : }
238
239       Note that "if" doesn't require parens, so the following code is okay:
240
241           : if ($var + 10) == 20 { } # OK
242
243       "given-when"(also known as switch statement):
244
245           : given $var {
246           :   when "foo" {
247                   it is foo.
248           :   }
249           :   when ["bar", "baz" ] {
250                   it is either bar or baz.
251           :   }
252           :   default {
253                   it is not foo nor bar.
254               }
255           : }
256
257       You can specify the topic variable.
258
259           : given $var -> $it {
260           :   when "foo" {
261                   it is foo.
262           :   }
263           :   when $it == "bar" or $it == "baz" {
264                   it is either bar or baz.
265           :   }
266           : }
267
268   Functions and filters
269       You can register functions via "function" or "module" options for
270       "Text::Xslate->new()".
271
272       Once you have registered functions, you can call them with the "()"
273       operator.  "infix:<|>" is also supported as a syntactic sugar to "()".
274
275           : f()        # without args
276           : f(1, 2, 3) # with args
277           : 42 | f     # the same as f(42)
278
279       Functions are just Perl's subroutines, so you can define dynamic
280       functions (a.k.a. dynamic filters), which is a subroutine that returns
281       another subroutine:
282
283           # code
284           sub mk_indent {
285               my($prefix) = @_;
286               return sub {
287                   my($str) = @_;
288                   $str =~ s/^/$prefix/xmsg;
289                   return $str;
290               }
291           }
292           my $tx = Text::Xslate->new(
293               function => {
294                   indent => \&mk_indent,
295               },
296           );
297
298           :# template
299           : $value | indent("> ") # Template-Toolkit like
300           : indent("> ")($value)  # This is also valid
301
302       "example/dynamic_functions.tx" has examples of dynamic functions being
303       used with block, function and filter syntax, and with scalar, hash and
304       array objects.
305
306       There are several builtin functions, which you cannot redefine:
307
308           : $var | mark_raw   # marks it as a raw string
309           : $var | raw        # synonym to mark_raw
310           : $var | unmark_raw # removes "raw" marker from it
311           : $var | html       # does html-escape to it and marks it as raw
312           : $var | dump       # dumps it with Data::Dumper
313
314       Note that you should not use "mark_raw" in templates because it can
315       make security hole easily just like as type casts in C. If you want to
316       generate HTML components dynamically, e.g. by HTML form builders,
317       application code should be responsible to make strings as marked "raw".
318
319   Methods
320       When $var is an object instance, you can call its methods with the dot
321       operator.
322
323           <: $var.method() :>
324           <: $var.method(1, 2, 3) :>
325           <: $var.method( foo => [ 1, 2, 3 ] ) :>
326
327       There is an autoboxing mechanism that provides primitive types with
328       builtin methods. See Text::Xslate::Manual::Builtin for details.
329
330       You can define more primitive methods with the "function" option. See
331       Text::Xslate.
332
333   Template inclusion
334       Template inclusion is a traditional way to extend templates.
335
336           : include "foo.tx";
337           : include "foo.tx" { var1 => value1, var2 => value2, ... };
338           : include "foo.tx" {$vars}; # use $vars as the params
339
340       if a var exist in the {$vars} and __ROOT__, the one in {$vars} will
341       win.
342
343       also, be careful about the order of vars.
344
345           : include "foo.tx" { var1 => $id, id => $var, var2 => $id }
346
347       var1 and var2 will be replaced by $id, var2 will be replaced by $var,
348       because the value of id is changed
349
350       As "cascade" does, "include" allows barewords:
351
352           : include foo      # the same as 'foo.tx'
353           : include foo::bar # the same as 'foo/bar.tx'
354
355       Xslate templates may be recursively included, but the including depth
356       is limited to 100.
357
358   Template cascading
359       Template cascading is another way to extend templates other than
360       "include".
361
362       First, make base templates myapp/base.tx:
363
364           : block title -> { # with default
365               [My Template!]
366           : }
367
368           : block body -> { } # without default
369
370       Then extend from base templates with the "cascade" keyword:
371
372           : cascade myapp::base
373           : cascade myapp::base { var1 => value1, var2 => value2, ...}
374           : cascade myapp::base with myapp::role1, myapp::role2
375           : cascade with myapp::role1, myapp::role2
376
377       In derived templates, you may extend templates (e.g. myapp/foo.tx) with
378       block modifiers "before", "around" (or "override") and "after".
379
380           : # cascade "myapp/base.tx" is also okay
381           : cascade myapp::base
382           : # use default title
383           : around body -> {
384               My template body!
385           : }
386
387       And, make yet another derived template myapp/bar.tx:
388
389           : cascade myapp::foo
390           : around title -> {
391               --------------
392               : super
393               --------------
394           : }
395           : before body -> {
396               Before body!
397           : }
398           : after body -> {
399               After body!
400           : }
401
402       Then render it as usual.
403
404           my $tx = Text::Xslate->new( file => 'myapp/bar.tx' );
405           $tx->render({});
406
407       The result is something like this:
408
409               --------------
410               [My Template!]
411               --------------
412
413               Before body!
414               My template body!
415               After body!
416
417       You can also cascade templates just like Moose's roles:
418
419           : cascade myapp::base with myapp::role1, myapp::role2
420
421       You can omit the base template.
422
423       Given a file myapp/hello.tx:
424
425           : around hello -> {
426               --------------
427               : super
428               --------------
429           : }
430
431       Then the main template:
432
433           : cascade with myapp::hello
434
435           : block hello -> {
436               Hello, world!
437           : }
438
439       Output:
440
441               --------------
442               Hello, world!
443               --------------
444
445       In fact, you can omit the base template, and components can include any
446       macros.
447
448       Given a file common.tx
449
450           : macro hello -> $lang {
451               Hello, <: $lang :> world!
452           : }
453
454           : around title -> {
455               --------------
456               : super
457               --------------
458           : }
459
460       The main template:
461
462           : cascade with common
463
464           : block title -> {
465               Hello, world!
466           : }
467           : hello("Xslate")
468
469       Output:
470
471               --------------
472               Hello, world!
473               --------------
474           Hello, Xslate world!
475
476       There is a limitation that you cannot pass variables to the "cascade"
477       keyword, because template cascading is statically processed.
478
479   Macro blocks
480       Macros are supported, which are called in the same way as functions and
481       return a "raw" string. Macros return what their bodies render, so they
482       cannot return references or objects, including other macros.
483
484           : macro add ->($x, $y) {
485           :   $x + $y;
486           : }
487           : add(10, 20)
488
489           : macro signature -> {
490               This is foo version <: $VERSION :>
491           : }
492           : signature()
493
494           : macro factorial -> $x {
495           :   $x == 0 ? 1 : $x * factorial($x-1)
496           : }
497           : factorial(1)  # as a function
498           : 1 | factorial # as a filter
499
500       If you want to html-escape the return values of macros, you can use
501       "unmark_raw" to remove "raw-ness" from the values.
502
503           : macro em -> $s {
504           <em><: $s :></em>
505           : }
506           : em("foo")               # renders "<em>foo</em>"
507           : em("foo") | unmark_raw  # renders "&lt;em&gt;foo&lt;em&gt;"
508
509       Because macros are first-class objects, you can bind them to symbols.
510
511           <: macro foo -> { "foo" }
512              macro bar -> { "bar" }
513              my $dispatcher = {
514                  foo => foo,
515                  bar => bar,
516              }; -:>
517           : $dispatcher{$key}()
518
519       Anonymous macros are also supported, although they can return only
520       strings. They might be useful for callbacks to high-level functions or
521       methods.
522
523           <: -> $x, $y { $x + $y }(1, 2) # => 3 :>
524
525       The "block" keyword is used to make a group of template code, and you
526       can apply filters to that block with "infix:<|>".  Here is an example
527       to embed HTML source code into templates.
528
529       Template:
530
531           : block source | unmark_raw -> {
532               <em>Hello, world!</em>
533           : }
534
535       Output:
536
537           &lt;em&gt;Hello, world!&lt;/em&gt;
538
539       See also "Using FillInForm" in Text::Xslate::Manual::Cookbook for
540       another example to use this block filter syntax.
541
542       Note that closures are not supported.
543
544   Chomping newlines
545       You can add "-" to the immediate start or end of a directive tag to
546       control the newline chomping options to keep the output clean. The
547       starting "-" removes leading newlines and the ending "-" removes
548       trailing ones.
549
550   Special keywords
551       There are special keywords:
552
553       __FILE__
554           Indicates the current file name. Equivalent to
555           "Text::Xslate->current_file".
556
557       __LINE__
558           Indicates the current line number. Equivalent to
559           "Text::Xslate->current_line".
560
561       __ROOT__
562           Means the root of the parameters. Equivalent to
563           "Text::Xslate->current_vars".
564
565   Comments
566       Comments start from "#" to a new line or semicolon.
567
568           :# this is a comment
569           <:
570             # this is also a comment
571             $foo # $foo is rendered
572           :>
573
574           <: $bar # this is ok :>
575           <: # this is comment; $baz # $baz is rendered :>
576

SEE ALSO

578       Text::Xslate
579
580
581
582perl v5.32.0                      2020-07-28    Text::Xslate::Syntax::Kolon(3)
Impressum