HTML::...uilder(3pm)
π HTML::HTML5::Builder π
okay bestie, so picture this: you're building an HTML5 document in Perl and you want it to look good without hand-typing a billion angle brackets. Welcome to HTML::HTML5::Builder, aka the module that will literally erect some scaffolding for your documents. iconic behavior. periodt.
β¨ SYNOPSIS β¨
use HTML::HTML5::Builder qw[:standard JQUERY];
open my $fh, '<', 'inline-script.js';
print html(
-lang => 'en',
head(
title('Test'),
Meta(-charset => 'utf-8'),
),
body(
h1('Test'),
p('This is a test.'),
JQUERY(-version => '1.6.4'),
script(-type => 'text/javascript', $fh),
),
);
look at that. a whole document. no cap. π
πΈ DESCRIPTION πΈ
So this module can export function names for literally any HTML5 element. Every HTML5 element. the whole roster. π
Each function returns an XML::LibXML::Element with the same name as the function. The arguments you pass to each function get processed as a list, and they're used to set the attributes and the contents of that element. it's giving "one function, so much power."
So for each item on that list, here's the vibe check:
- if it's an
XML::LibXML::Element,XML::LibXML::TextNode,XML::LibXML::Comment, orXML::LibXML::PI, it gets appended as a child of the element you're returning. cute, adopted. π«Ά - if it's an
XML::LibXML::NodeList, then every item in that list gets appended as a child of the returned element. it's a whole friend group moving in together. - if it's an
XML::LibXML::Attr, it gets set as an attribute on the returned element. - if it's an
IO::Handle, then it will be slurped up and appended to the returned element as a text node. glug glug. π - if it's a scalar reference, then the returned element is also assigned to it. (bestie, this feature is at risk. like, "we're keeping an eye on it" at risk.)
- if it's a scalar (a string), some guesswork happens β the module is out here doing detective work π΅οΈ to figure out whether you're setting an attribute and value, or whether that string should just be used as a text node. The main deciding factor is whether there's a hyphen at the start of the string.
p('-class', 'warning', '$LordLucan not found.');
So in that example up there, you get a paragraph element back, with the class attribute set to 'warning' and the textual contents '$LordLucan not found.'. slay.
Sometimes you gotta protect your values from all that guesswork though. So: if you pass a hashref, all the keys and values are interpreted as setting attributes; if you pass an arrayref, all the values are interpreted as setting the contents of the element.
p(['-class'], { warning => '$LordLucan not found.' });
In that example, you get a paragraph element with the warning attribute set to '$LordLucan not found.' and the textual contents '-class'. yes, it flipped around. the hashref won. π
- Anything else gets stringified and added as a text node. This is lowkey useful for things with sensible stringification defined, like
DateTimeandURIobjects β but highkey less useful for some other objects, so you'll sometimes get a warning if warnings are enabled. You can turn those off with:
no warnings 'HTML::HTML::Builder';
π¦ Exceptional Cases π¦
The html function does not return an XML::LibXML::Element β it returns a HTML::HTML5::Builder::Document object instead. main character energy, different return type, we don't question it. π
There's also special handling for time (or Time). If the first parameter you pass to it is a DateTime object, then that object is used to set its datetime attribute. And if there are no subsequent parameters after that, then the stringified form of the object is also used to form the content of the <time> element. two for one, we love a multitasker. β¨
Now important PSA time: the functions that generate <meta>, <link>, <q>, <time>, <sub>, <s> and <map> HTML elements are named Meta(), Link(), Q(), Time(), Sub(), S() and Map() respectively β with an upper-case first letter. Why? because every one of those names collides with a built-in perl keyword (except meta, which is used by Moose). The lower-case versions of these do exist and can be exported if you ask for them explicitly, and the lower-case versions are also available as methods using the object-oriented syntax. (Honestly? lower case and ucfirst versions exist for all HTML elements β they're just not always exportable. iykyk.) π
π General Purpose Functions π
ELEMENT($tagname, @arguments)β for when you need to insert an element that doesn't have its own dedicated function. the DIY option.TEXT($string)β produces a text node. simple, elegant, no notes. β¨COMMENT($string)β produces an HTML comment.<!-- hi bestie -->vibes.CHUNK($string)β parses the string as HTML and produces a list of elements, text nodes and comments.
This should be a so-called "balanced chunk". Due to limitations in HTML::HTML5::Parser, this only works for body content. And it croaks if HTML::HTML5::Parser is not installed. π so install it, bestie.
XML_CHUNK($string)β the more useful version ofCHUNK, without the content restriction β but the input needs to be a balanced and well-formed XML chunk. no chaos allowed in this one.RAW_CHUNK($string)β this lets you shove stuff that is nowhere near valid HTML into the output document, like a PHP block. e.g.
html(
head(
title('Funny test'),
),
body(
h1('Funny test'),
RAW_CHUNK("<p>Here's a fish: <=><"),
),
);
A processing instruction is used to represent this data in the DOM. HTML::HTML5::Writer can detect that processing instruction and use it to output the raw data. But if you're not using HTML::HTML5::Writer to serialise the document, then you may need to post-process the serialised document yourself. π
With great power comes great responsibility. π·οΈ
π Boiler-Plate Functions π
There are also a bunch of functions that create lists of multiple HTML elements, for that boiler-plate code you keep writing over and over.
JQUERY(-version => $ver, %options)β links to jQuery at a CDN. π₯
Other options include -source, to indicate where to link to jQuery (currently the allowed values are "Google", "Microsoft" and "official"); and -min, a boolean that says whether the minified version should be linked to (true by default).
Setting the option -ui to true also includes jQuery UI. A version number can be indicated using -ui_version. A theme can be included by setting -theme. And setting either -ui_version or -theme will imply -ui. sneaky but helpful.
JQUERY(
-source => 'official',
-version => '1.6.4',
-ui_version => '1.8.16',
-theme => 'eggplant',
);
If versions aren't provided, it defaults to the latest versions of the libraries that the author of HTML::HTML5::Builder was aware of at the time of publication. (so like, a time capsule, kinda. π°οΈ) And if you choose a version which is known to be unavailable at the selected CDN, the function should automatically choose a slightly later version. it's got your back. π
CREATIVE_COMMONS($licence)CREATIVE_COMMONS(-licence => $licence, %options)
$licence can be one of 'by', 'by-nd', 'by-nc', 'by-sa', 'by-sa-nc', or 'by-sa-nd'.
Other options supported are:
-urlβ URL of the thing being licensed (if it's not the page itself)-sizeβ'large'or'small'for the image-titleβ title of the work-attributionNameβ name people should use for attribution-attributionURLβ link people should use for attribution
OPENGRAPH(%data)β returns a list of<meta>elements providing Open Graph Protocol data for your page. so when your link gets dropped in the group chat, it looks good. β¨
OPENGRAPH(
-title => "Hello World",
-type => "example",
-description => "A global greeting.",
);
π Exporting Functions π
None by default. nope, not a single one. π Pretty much anything can be exported on request though β you just gotta ask.
Export tags:
:allβ everything. the whole closet. π:standardβ elements that are not obsolete in HTML5, plusELEMENT,TEXT,COMMENT,CHUNK,XML_CHUNKandRAW_CHUNK:metadataβhead title base Link Meta style:sectionsβbody div section nav article aside h1 h2 h3 h4 h5 h6 header footer address:groupingβp hr br pre dialog blockquote ol ul li dl dt dd:textβa Q cite em strong small mark dfn abbr progress meter code var samp kbd Sub sup span i b bdo ruby rt rp Time:embeddedβfigure img iframe embed object param video audio source canvas area:tabularβtable thead tbody tfoot th td colgroup col caption:formβform fieldset label input button select datalist optgroup option textarea output
π§ Object Oriented Interface π§
You can also use all these functions as methods of an object blessed into the HTML::HTML5::Builder package. yes, she contains multitudes. π
my $b = HTML::HTML5::Builder->new;
my $document = $b->html(
-lang => 'en',
$b->head(
$b->title('Test', \(my $foo)),
$b->meta(-charset => 'utf-8'),
),
$b->body(
$b->h1('Test'),
$b->p('This is a test.')
),
);
β Using with RDF::RDFa::Generator β
RDF::RDFa::Generator has a nodes method which returns a handy list of XML::LibXML::Node objects. cute little handoff. π«Ά
use DateTime;
use HTML::HTML5::Builder qw[:standard];
use RDF::RDFa::Generator;
use RDF::Trine;
my $url = 'http://dbpedia.org/data/Charles_Darwin';
my $model = RDF::Trine::Model->new;
RDF::Trine::Parser->parse_url_into_model($url, $model);
my $gen = RDF::RDFa::Generator->new(style=>'HTML::Pretty');
print html(
head(
title("Some Data About Charles Darwin"),
),
body(
h1("Some Data About Charles Darwin"),
$gen->nodes($model),
hr(),
address(
"Source: $url", br(),
"Generated: ", Time(DateTime->now),
),
),
);
Nice? πβ¨
πΈ Using with XML::LibXML::PrettyPrint πΈ
HTML::HTML5::Builder doesn't nicely indent your markup β like, it's not gonna make it all pretty for you β but XML::LibXML::PrettyPrint can. β¨
use HTML::HTML5::Builder qw(:standard);
use XML::LibXML::PrettyPrint qw(print_xml);
print_xml html(
head(title("Test")),
body(h1("Test"), p("This is a test.")),
);
π BUGS π
Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=HTML-HTML5-Builder>.
(no gatekeeping bug reports, we tell the maintainers. that's the vibe.)
π SEE ALSO π
XML::LibXML, HTML::HTML5::Writer, HTML::HTML5::Builder::Document.
π AUTHOR π
Toby Inkster <tobyink@cpan.org>.
π COPYRIGHT AND LICENCE π
This software is copyright (c) 2011 by Toby Inkster.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. free as in bestie, fr fr.
π«Ά DISCLAIMER OF WARRANTIES π«Ά
THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
(no promises, no drama, that's just how it is. π)
that's the page bestie β from perl v5.40.1, dated 2025-08-23. go build something iconic. π
β¨ππ¦
π¦ where this page comes from
- ubuntu resolute: libhtml-html5-builder-perl 0.004-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libhtml-html5-builder-perl 0.004-6 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms