HTML-Composer
view release on metacpan or search on metacpan
lib/HTML/Composer.pm view on Meta::CPAN
]
]
]
);
This will output the following HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Site</title>
<script src="/js/myScript.js" type="text/javascript"></script>
</head>
<body>
<h1>Hello World</h1>
<br>
<div class="p-3 background-red">
Hello World!
<h2>Test 123</h2>
</div>
</body>
</html>
HTML elements that allow children are created like:
[div => ["Text!", h1 => ["Text!"]]] # <div>Text!<h1>Text!</h1></div>
To provide attributes to a tag:
[div => { class => ["p-3", "m-2"] } => ["Text!", h1 => ["Text!"]]] # <div class="p-3 m-2">Text!<h1>Text!</h1></div>
If a tag doesn't have any children, ie a <link> tag:
[link => { href => "www.google.com" }] # <link href="www.google.com">
If a tag doesn't have any attributes:
[br => {}] # <br>
To render just text, make sure it isn't followed up by an array, or hash:
["Text!"]
=cut
use strict;
use warnings;
use feature qw(state);
use Carp qw(croak);
use HTML::Escape qw(escape_html);
use Sereal::Encoder;
use HTML::Composer::Unsafe;
my @tags_list = qw(
a abbr address area article aside audio b base bdi bdo blockquote body
br button canvas caption cite code col colgroup data datalist dd del
details dfn dialog div dl dt em embed fieldset figcaption figure
footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe
img input ins kbd label legend li link main map mark menu meta
meter nav noscript object ol optgroup option output p param picture
plaintext pre progress q rp rt ruby s samp script search section
select slot small source span strong style sub summary sup table
tbody td template textarea tfoot th thead time title tr track u
ul var video wbr
);
my %tags_map = map { $_ => 1 } @tags_list;
=head2 new(%ARGS)
Create a new instance of HTML::Composer. Optionally, pass a cache argument, to tell
HTML::Hash to cache the result against the hash you pass. (Caching defaults to false).
my $h = HTML::Composer->new(); # Cached instance of HTML::Composer
$h->html(...);
my $hc = HTML::Composer->new(cache => 0); # Don't cache templates
$hc->html(...);
=cut
sub new {
my ( $class, %args ) = @_;
return bless {
cache => $args{cache} // 0,
store => {},
encoder => Sereal::Encoder->new(
{
snappy => 1,
croak_on_bless => 1,
stringify_unknown => 1,
canonical => 1
}
)
}, $class;
}
=head2 html(ARRAY)
Create a string containing the HTML page described in ARRAY. Croaks if HTML validation fails.
my $h = HTML::Composer->new();
my $html = $h->html([
head => [
title => ["My Site"],
script => {
src => "/js/myScript.js",
type => "text/javascript"
}
],
body => [
h1 => ["Hello World!"],
br => {},
div => { class => [ "p-3", "background-red" ] } => [
"Hello World!", h2 => ["Test 123"]
]
]
]
);
( run in 0.500 second using v1.01-cache-2.11-cpan-9581c071862 )