Overview
We will introduce you to the most simple usage of Xslate.
Main subjects of this page are listed below:
- Iteration
- The dump filter - useful for debugging
- mark_raw() - To output a text without escaping
Example
$books(hashref) contains information of Perl books.$htmlcontains a HTML source string. You must usemark_raw()in applications in order to interpolate HTML sources into templates. Otherwise meta characters in template variables will be escaped automatically.
Script: perlbook.pl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use Encode qw(encode_utf8);
use FindBin qw($Bin);
use Text::Markdown qw(markdown);
use Text::Xslate qw(mark_raw);
my $xslate = Text::Xslate->new(
path => ["$Bin/templates"],
);
my $books = {
"978-0596000271" => {
name => "Programming Perl",
pages => 1092,
},
# Programming Perl in Russian
"978-5932860205" => {
name => "Программирование на Perl",
pages => 1152,
},
# Programming Perl in Japanese
"978-4873110967" => {
name => "プログラミングPerl Vol.1",
pages => 708,
},
"978-4873110974" => {
name => "プログラミングPerl Vol.2",
pages => 1303,
},
};
my $see_also = markdown(<<'END_MD'); # an HTML generator
SEE ALSO
-----------------
* http://perl.com/
* http://perl.org/
* http://search.cpan.org/
END_MD
my $content = $xslate->render("perlbook.tx", {
title => "Perl Books",
books => $books,
see_also => mark_raw($see_also),
});
print encode_utf8($content);
__END__
Template: templates/perlbook.tx
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title><: $title :></title>
</head>
<body>
<h1><: $title :></h1>
<ol>
: for $books.keys() -> $isbn {
<li><: $books[$isbn].name :> - <: $books[$isbn].pages :> pages / ISBN-13 : <: $isbn :></li>
: }
</ol>
<pre>
$books =
: $books | dump
</pre>
: $see_also # interpolate HTML components
</body>
</html>
Output:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Perl Books</title>
</head>
<body>
<h1>Perl Books</h1>
<ol>
<li>Programming Perl - 1092 pages / ISBN-13 : 978-0596000271</li>
<li>プログラミングPerl Vol.1 - 708 pages / ISBN-13 : 978-4873110967</li>
<li>プログラミングPerl Vol.2 - 1303 pages / ISBN-13 : 978-4873110974</li>
<li>Программирование на Perl - 1152 pages / ISBN-13 : 978-5932860205</li>
</ol>
<pre>
$books =
(
'978-0596000271' => {
name => 'Programming Perl',
pages => 1092
},
'978-4873110967' => {
name => 'プログラミングPerl Vol.1',
pages => 708
},
'978-4873110974' => {
name => 'プログラミングPerl Vol.2',
pages => 1303
},
'978-5932860205' => {
name => 'Программирование на Perl',
pages => 1152
}
)
</pre>
<h2>SEE ALSO</h2>
<ul>
<li>http://perl.com/</li>
<li>http://perl.org/</li>
<li>http://search.cpan.org/</li>
</ul>
</body>
</html>