1Mojo::Template(3)     User Contributed Perl Documentation    Mojo::Template(3)
2
3
4

NAME

6       Mojo::Template - Perl-ish templates
7

SYNOPSIS

9         use Mojo::Template;
10
11         # Use Perl modules
12         my $mt = Mojo::Template->new;
13         say $mt->render(<<'EOF');
14         % use Time::Piece;
15         <div>
16           % my $now = localtime;
17           Time: <%= $now->hms %>
18         </div>
19         EOF
20
21         # Render with arguments
22         say $mt->render(<<'EOF', [1 .. 13], 'Hello World!');
23         % my ($numbers, $title) = @_;
24         <div>
25           <h1><%= $title %></h1>
26           % for my $i (@$numbers) {
27             Test <%= $i %>
28           % }
29         </div>
30         EOF
31
32         # Render with named variables
33         say $mt->vars(1)->render(<<'EOF', {title => 'Hello World!'});
34         <div>
35           <h1><%= $title %></h1>
36           %= 5 + 5
37         </div>
38         EOF
39

DESCRIPTION

41       Mojo::Template is a minimalistic, fast, and very Perl-ish template
42       engine, designed specifically for all those small tasks that come up
43       during big projects. Like preprocessing a configuration file,
44       generating text from heredocs and stuff like that.
45
46       See Mojolicious::Guides::Rendering for information on how to generate
47       content with the Mojolicious renderer.
48

SYNTAX

50       For all templates strict, warnings, utf8 and Perl 5.16 features are
51       automatically enabled.
52
53         <% Perl code %>
54         <%= Perl expression, replaced with result %>
55         <%== Perl expression, replaced with XML escaped result %>
56         <%# Comment, useful for debugging %>
57         <%% Replaced with "<%", useful for generating templates %>
58         % Perl code line, treated as "<% line =%>" (explained later)
59         %= Perl expression line, treated as "<%= line %>"
60         %== Perl expression line, treated as "<%== line %>"
61         %# Comment line, useful for debugging
62         %% Replaced with "%", useful for generating templates
63
64       Escaping behavior can be reversed with the "auto_escape" attribute,
65       this is the default in Mojolicious ".ep" templates, for example.
66
67         <%= Perl expression, replaced with XML escaped result %>
68         <%== Perl expression, replaced with result %>
69
70       Mojo::ByteStream objects are always excluded from automatic escaping.
71
72         % use Mojo::ByteStream qw(b);
73         <%= b('<div>excluded!</div>') %>
74
75       Whitespace characters around tags can be trimmed by adding an
76       additional equal sign to the end of a tag.
77
78         <% for (1 .. 3) { %>
79           <%= 'Trim all whitespace characters around this expression' =%>
80         <% } %>
81
82       Newline characters can be escaped with a backslash.
83
84         This is <%= 1 + 1 %> a\
85         single line
86
87       And a backslash in front of a newline character can be escaped with
88       another backslash.
89
90         This will <%= 1 + 1 %> result\\
91         in multiple\\
92         lines
93
94       A newline character gets appended automatically to every template,
95       unless the last character is a backslash. And empty lines at the end of
96       a template are ignored.
97
98         There is <%= 1 + 1 %> no newline at the end here\
99
100       You can capture whole template blocks for reuse later with the "begin"
101       and "end" keywords. Just be aware that both keywords are part of the
102       surrounding tag and not actual Perl code, so there can only be
103       whitespace after "begin" and before "end".
104
105         <% my $block = begin %>
106           <% my $name = shift; =%>
107           Hello <%= $name %>.
108         <% end %>
109         <%= $block->('Baerbel') %>
110         <%= $block->('Wolfgang') %>
111
112       Perl lines can also be indented freely.
113
114         % my $block = begin
115           % my $name = shift;
116           Hello <%= $name %>.
117         % end
118         %= $block->('Baerbel')
119         %= $block->('Wolfgang')
120
121       Mojo::Template templates get compiled to a Perl subroutine, that means
122       you can access arguments simply via @_.
123
124         % my ($foo, $bar) = @_;
125         % my $x = shift;
126         test 123 <%= $foo %>
127
128       The compilation of templates to Perl code can make debugging a bit
129       tricky, but Mojo::Template will return Mojo::Exception objects that
130       stringify to error messages with context.
131
132         Bareword "xx" not allowed while "strict subs" in use at template line 4.
133         Context:
134           2: </head>
135           3: <body>
136           4: % my $i = 2; xx
137           5: %= $i * 2
138           6: </body>
139         Traceback (most recent call first):
140           File "template", line 4, in "Mojo::Template::Sandbox"
141           File "path/to/Mojo/Template.pm", line 123, in "Mojo::Template"
142           File "path/to/myapp.pl", line 123, in "main"
143

ATTRIBUTES

145       Mojo::Template implements the following attributes.
146
147   auto_escape
148         my $bool = $mt->auto_escape;
149         $mt      = $mt->auto_escape($bool);
150
151       Activate automatic escaping.
152
153         # "&lt;html&gt;"
154         Mojo::Template->new(auto_escape => 1)->render("<%= '<html>' %>");
155
156   append
157         my $code = $mt->append;
158         $mt      = $mt->append('warn "Processed template"');
159
160       Append Perl code to compiled template. Note that this code should not
161       contain newline characters, or line numbers in error messages might end
162       up being wrong.
163
164   capture_end
165         my $end = $mt->capture_end;
166         $mt     = $mt->capture_end('end');
167
168       Keyword indicating the end of a capture block, defaults to "end".
169
170         <% my $block = begin %>
171           Some data!
172         <% end %>
173
174   capture_start
175         my $start = $mt->capture_start;
176         $mt       = $mt->capture_start('begin');
177
178       Keyword indicating the start of a capture block, defaults to "begin".
179
180         <% my $block = begin %>
181           Some data!
182         <% end %>
183
184   code
185         my $code = $mt->code;
186         $mt      = $mt->code($code);
187
188       Perl code for template if available.
189
190   comment_mark
191         my $mark = $mt->comment_mark;
192         $mt      = $mt->comment_mark('#');
193
194       Character indicating the start of a comment, defaults to "#".
195
196         <%# This is a comment %>
197
198   compiled
199         my $compiled = $mt->compiled;
200         $mt          = $mt->compiled($compiled);
201
202       Compiled template code if available.
203
204   encoding
205         my $encoding = $mt->encoding;
206         $mt          = $mt->encoding('UTF-8');
207
208       Encoding used for template files, defaults to "UTF-8".
209
210   escape
211         my $cb = $mt->escape;
212         $mt    = $mt->escape(sub {...});
213
214       A callback used to escape the results of escaped expressions, defaults
215       to "xml_escape" in Mojo::Util.
216
217         $mt->escape(sub {
218           my $str = shift;
219           return reverse $str;
220         });
221
222   escape_mark
223         my $mark = $mt->escape_mark;
224         $mt      = $mt->escape_mark('=');
225
226       Character indicating the start of an escaped expression, defaults to
227       "=".
228
229         <%== $foo %>
230
231   expression_mark
232         my $mark = $mt->expression_mark;
233         $mt      = $mt->expression_mark('=');
234
235       Character indicating the start of an expression, defaults to "=".
236
237         <%= $foo %>
238
239   line_start
240         my $start = $mt->line_start;
241         $mt       = $mt->line_start('%');
242
243       Character indicating the start of a code line, defaults to "%".
244
245         % $foo = 23;
246
247   name
248         my $name = $mt->name;
249         $mt      = $mt->name('foo.mt');
250
251       Name of template currently being processed, defaults to "template".
252       Note that this value should not contain quotes or newline characters,
253       or error messages might end up being wrong.
254
255   namespace
256         my $namespace = $mt->namespace;
257         $mt           = $mt->namespace('main');
258
259       Namespace used to compile templates, defaults to
260       "Mojo::Template::SandBox". Note that namespaces should only be shared
261       very carefully between templates, since functions and global variables
262       will not be cleared automatically.
263
264   prepend
265         my $code = $mt->prepend;
266         $mt      = $mt->prepend('my $self = shift;');
267
268       Prepend Perl code to compiled template. Note that this code should not
269       contain newline characters, or line numbers in error messages might end
270       up being wrong.
271
272   replace_mark
273         my $mark = $mt->replace_mark;
274         $mt      = $mt->replace_mark('%');
275
276       Character used for escaping the start of a tag or line, defaults to
277       "%".
278
279         <%% my $foo = 23; %>
280
281   tag_start
282         my $start = $mt->tag_start;
283         $mt       = $mt->tag_start('<%');
284
285       Characters indicating the start of a tag, defaults to "<%".
286
287         <% $foo = 23; %>
288
289   tag_end
290         my $end = $mt->tag_end;
291         $mt     = $mt->tag_end('%>');
292
293       Characters indicating the end of a tag, defaults to "%>".
294
295         <%= $foo %>
296
297   tree
298         my $tree = $mt->tree;
299         $mt      = $mt->tree([['text', 'foo'], ['line']]);
300
301       Template in parsed form if available. Note that this structure should
302       only be used very carefully since it is very dynamic.
303
304   trim_mark
305         my $mark = $mt->trim_mark;
306         $mt      = $mt->trim_mark('-');
307
308       Character activating automatic whitespace trimming, defaults to "=".
309
310         <%= $foo =%>
311
312   unparsed
313         my $unparsed = $mt->unparsed;
314         $mt          = $mt->unparsed('<%= 1 + 1 %>');
315
316       Raw unparsed template if available.
317
318   vars
319         my $bool = $mt->vars;
320         $mt      = $mt->vars($bool);
321
322       Instead of a list of values, use a hash reference with named variables
323       to pass data to templates.
324
325         # "works!"
326         Mojo::Template->new(vars => 1)->render('<%= $test %>!', {test => 'works'});
327

METHODS

329       Mojo::Template inherits all methods from Mojo::Base and implements the
330       following new ones.
331
332   parse
333         $mt = $mt->parse('<%= 1 + 1 %>');
334
335       Parse template into "tree".
336
337   process
338         my $output = $mt->process;
339         my $output = $mt->process(@args);
340         my $output = $mt->process({foo => 'bar'});
341
342       Process previously parsed template and return the result, or a
343       Mojo::Exception object if rendering failed.
344
345         # Parse and process
346         say Mojo::Template->new->parse('Hello <%= $_[0] %>')->process('Bender');
347
348         # Reuse template (for much better performance)
349         my $mt = Mojo::Template->new;
350         say $mt->render('Hello <%= $_[0] %>!', 'Bender');
351         say $mt->process('Fry');
352         say $mt->process('Leela');
353
354   render
355         my $output = $mt->render('<%= 1 + 1 %>');
356         my $output = $mt->render('<%= shift() + shift() %>', @args);
357         my $output = $mt->render('<%= $foo %>', {foo => 'bar'});
358
359       Render template and return the result, or a Mojo::Exception object if
360       rendering failed.
361
362         # Longer version
363         my $output = $mt->parse('<%= 1 + 1 %>')->process;
364
365         # Render with arguments
366         say Mojo::Template->new->render('<%= $_[0] %>', 'bar');
367
368         # Render with named variables
369         say Mojo::Template->new(vars => 1)->render('<%= $foo %>', {foo => 'bar'});
370
371   render_file
372         my $output = $mt->render_file('/tmp/foo.mt');
373         my $output = $mt->render_file('/tmp/foo.mt', @args);
374         my $output = $mt->render_file('/tmp/bar.mt', {foo => 'bar'});
375
376       Same as "render", but renders a template file.
377

DEBUGGING

379       You can set the "MOJO_TEMPLATE_DEBUG" environment variable to get some
380       advanced diagnostics information printed to "STDERR".
381
382         MOJO_TEMPLATE_DEBUG=1
383

SEE ALSO

385       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
386
387
388
389perl v5.32.0                      2020-07-28                 Mojo::Template(3)
Impressum