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 ($str) { return reverse $str });
218
219   escape_mark
220         my $mark = $mt->escape_mark;
221         $mt      = $mt->escape_mark('=');
222
223       Character indicating the start of an escaped expression, defaults to
224       "=".
225
226         <%== $foo %>
227
228   expression_mark
229         my $mark = $mt->expression_mark;
230         $mt      = $mt->expression_mark('=');
231
232       Character indicating the start of an expression, defaults to "=".
233
234         <%= $foo %>
235
236   line_start
237         my $start = $mt->line_start;
238         $mt       = $mt->line_start('%');
239
240       Character indicating the start of a code line, defaults to "%".
241
242         % $foo = 23;
243
244   name
245         my $name = $mt->name;
246         $mt      = $mt->name('foo.mt');
247
248       Name of template currently being processed, defaults to "template".
249       Note that this value should not contain quotes or newline characters,
250       or error messages might end up being wrong.
251
252   namespace
253         my $namespace = $mt->namespace;
254         $mt           = $mt->namespace('main');
255
256       Namespace used to compile templates, defaults to
257       "Mojo::Template::Sandbox". Note that namespaces should only be shared
258       very carefully between templates, since functions and global variables
259       will not be cleared automatically.
260
261   prepend
262         my $code = $mt->prepend;
263         $mt      = $mt->prepend('my $self = shift;');
264
265       Prepend Perl code to compiled template. Note that this code should not
266       contain newline characters, or line numbers in error messages might end
267       up being wrong.
268
269   replace_mark
270         my $mark = $mt->replace_mark;
271         $mt      = $mt->replace_mark('%');
272
273       Character used for escaping the start of a tag or line, defaults to
274       "%".
275
276         <%% my $foo = 23; %>
277
278   tag_start
279         my $start = $mt->tag_start;
280         $mt       = $mt->tag_start('<%');
281
282       Characters indicating the start of a tag, defaults to "<%".
283
284         <% $foo = 23; %>
285
286   tag_end
287         my $end = $mt->tag_end;
288         $mt     = $mt->tag_end('%>');
289
290       Characters indicating the end of a tag, defaults to "%>".
291
292         <%= $foo %>
293
294   tree
295         my $tree = $mt->tree;
296         $mt      = $mt->tree([['text', 'foo'], ['line']]);
297
298       Template in parsed form if available. Note that this structure should
299       only be used very carefully since it is very dynamic.
300
301   trim_mark
302         my $mark = $mt->trim_mark;
303         $mt      = $mt->trim_mark('-');
304
305       Character activating automatic whitespace trimming, defaults to "=".
306
307         <%= $foo =%>
308
309   unparsed
310         my $unparsed = $mt->unparsed;
311         $mt          = $mt->unparsed('<%= 1 + 1 %>');
312
313       Raw unparsed template if available.
314
315   vars
316         my $bool = $mt->vars;
317         $mt      = $mt->vars($bool);
318
319       Instead of a list of values, use a hash reference with named variables
320       to pass data to templates.
321
322         # "works!"
323         Mojo::Template->new(vars => 1)->render('<%= $test %>!', {test => 'works'});
324

METHODS

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

DEBUGGING

376       You can set the "MOJO_TEMPLATE_DEBUG" environment variable to get some
377       advanced diagnostics information printed to "STDERR".
378
379         MOJO_TEMPLATE_DEBUG=1
380

SEE ALSO

382       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
383
384
385
386perl v5.36.0                      2022-07-22                 Mojo::Template(3)
Impressum