HTML::Tiny(3pm)
π HTML::Tiny π
okay bestie, buckle up β HTML::Tiny is the lightweight, dependency free HTML/XML generation module and she is that girl. β¨
πΈ SYNOPSIS πΈ
no cap, this is literally all it takes:
use HTML::Tiny;
my $h = HTML::Tiny->new;
# Generate a simple page
print $h->html(
[
$h->head( $h->title( 'Sample page' ) ),
$h->body(
[
$h->h1( { class => 'main' }, 'Sample page' ),
$h->p( 'Hello, World', { class => 'detail' }, 'Second para' )
]
)
]
);
# Outputs
<html>
<head>
<title>Sample page</title>
</head>
<body>
<h1 class="main">Sample page</h1>
<p>Hello, World</p>
<p class="detail">Second para</p>
</body>
</html>
likeβ¦ she ate. π
π¦ DESCRIPTION π¦
HTML::Tiny is a simple, dependency free module for generating HTML (and XML). She's hyper-focused on one thing: producing syntactically correct XHTML using a simple Perl notation. no drama, no CPAN cascade, just vibes.
On top of the HTML generation functions, she also hands you some utility functions so you can:
- encode and decode URL encoded strings π
- entity encode HTML π§
- build query strings π
- JSON encode data structures β
β¨ INTERFACE β¨
new
Creates a brand new HTML::Tiny. The constructor takes one optional argument: mode. And mode can be either 'xml' (the default) or 'html'.
The difference? In HTML mode, closed tags will not be closed with a forward slash β instead, closed tags get returned as single open tags. it's givingβ¦ different, but correct for HTML.
Example:
# Set HTML mode.
my $h = HTML::Tiny->new( mode => 'html' );
# The default is XML mode, but this can also be defined explicitly.
$h = HTML::Tiny->new( mode => 'xml' );
real talk: HTML is a dialect of SGML, and is not XML in any way. "Orphan" open tags or unclosed tags are legal and in fact expected by user agents. So in practice: if you want to generate XML or XHTML, supply no arguments. If you want valid HTML, use mode => 'html'. periodt.
π HTML Generation π
tag( $name, ... )
Returns HTML (or XML) that encloses each of the arguments in the specified tag. For example
print $h->tag('p', 'Hello', 'World');
would print
<p>Hello</p><p>World</p>
notice that each argument is individually wrapped in the specified tag. To avoid this, multiple arguments can be grouped in an anonymous array:
print $h->tag('p', ['Hello', 'World']);
would print
<p>HelloWorld</p>
You can think of the [ and ] as grouping a number of arguments together. iconic.
Attributes may be supplied by including an anonymous hash as the first element in the argument list (after the tag name):
print $h->tag('p', { class => 'normal' }, 'Foo');
would print
<p class="normal">Foo</p>
Attribute values will be HTML entity encoded as necessary. yes bestie, she handles that for you.
Multiple hashes may be supplied, in which case they will be merged:
print $h->tag('p',
{ class => 'normal' }, 'Bar',
{ style => 'color: red' }, 'Bang!'
);
would print
<p class="normal">Bar</p><p class="normal" style="color: red">Bang!</p>
Notice that the class="normal" attribute is merged with the style attribute for the second paragraph. lowkey obsessed with how tidy that is.
To remove an attribute, set its value to undef:
print $h->tag('p',
{ class => 'normal' }, 'Bar',
{ class => undef }, 'Bang!'
);
would print
<p class="normal">Bar</p><p>Bang!</p>
An empty attribute β such as 'checked' in a checkbox β can be encoded by passing an empty array reference:
print $h->closed( 'input', { type => 'checkbox', checked => [] } );
would print
<input checked type="checkbox" />
Return Value
In a scalar context tag returns a string. In a list context it returns an array, each element of which corresponds to one of the original arguments:
my @html = $h->tag('p', 'this', 'that');
would return
@html = (
'<p>this</p>',
'<p>that</p>'
);
That means that when you nest calls to tag (or the equivalent HTML aliases β see below), the individual arguments to the inner call will be tagged separately by each enclosing call. In practice this means that
print $h->tag('p', $h->tag('b', 'Foo', 'Bar'));
would print
<p><b>Foo</b></p><p><b>Bar</b></p>
You can modify this behavior by grouping multiple args in an anonymous array:
print $h->tag('p', [ $h->tag('b', 'Foo', 'Bar') ] );
would print
<p><b>Foo</b><b>Bar</b></p>
This behaviour is powerful but can take a little time to master. If you imagine [ and ] preventing the propagation of the 'tag individual items' behaviour, it might help visualise how it works. ngl, once it clicks it clicks. π‘
Here's an HTML table (using the tag-name convenience methods β see below) that demonstrates it in more detail:
print $h->table(
[
$h->tr(
[ $h->th( 'Name', 'Score', 'Position' ) ],
[ $h->td( 'Therese', 90, 1 ) ],
[ $h->td( 'Chrissie', 85, 2 ) ],
[ $h->td( 'Andy', 50, 3 ) ]
)
]
);
which would print the unformatted version of:
<table>
<tr><th>Name</th><th>Score</th><th>Position</th></tr>
<tr><td>Therese</td><td>90</td><td>1</td></tr>
<tr><td>Chrissie</td><td>85</td><td>2</td></tr>
<tr><td>Andy</td><td>50</td><td>3</td></tr>
</table>
Note how you don't need a td() for every cell or a tr() for every row. Notice also how the square brackets around the rows prevent tr() from wrapping each individual cell. π«Ά
Often when generating nested HTML you will find yourself writing corresponding nested calls to HTML generation methods. The table generation code above is an example of this.
If you prefer, these nested method calls can be deferred like this:
print $h->table(
[
\'tr',
[ \'th', 'Name', 'Score', 'Position' ],
[ \'td', 'Therese', 90, 1 ],
[ \'td', 'Chrissie', 85, 2 ],
[ \'td', 'Andy', 50, 3 ]
]
);
In general a nested call like
$h->method( args )
may be rewritten like this
[ \'method', args ]
This allows complex HTML to be expressed as a pure data structure. See the stringify method for more information. yeah, data structure main character energy. π
open( $name, ... )
Generate an opening HTML or XML tag. For example:
print $h->open('marker');
would print
<marker>
Attributes can be provided in the form of anonymous hashes in the same way as for tag. For example:
print $h->open('marker', { lat => 57.0, lon => -2 });
would print
<marker lat="57.0" lon="-2">
As for tag, multiple attribute hash references will be merged. The example above could be written:
print $h->open('marker', { lat => 57.0 }, { lon => -2 });
close( $name )
Generate a closing HTML or XML tag. For example:
print $h->close('marker');
would print:
</marker>
closed( $name, ... )
Generate a closed HTML or XML tag. For example
print $h->closed('marker');
would print:
<marker />
As for tag and open, attributes may be provided as hash references:
print $h->closed('marker', { lat => 57.0 }, { lon => -2 });
would print:
<marker lat="57.0" lon="-2" />
auto_tag( $name, ... )
Calls either tag or closed based on built in rules for the tag. Used internally to implement the tag-named methods. she's the backstage queen fr.
stringify( $obj )
Called internally to obtain string representations of values.
It also implements the deferred method call notation (mentioned above) so that
my $table = $h->table(
[
$h->tr(
[ $h->th( 'Name', 'Score', 'Position' ) ],
[ $h->td( 'Therese', 90, 1 ) ],
[ $h->td( 'Chrissie', 85, 2 ) ],
[ $h->td( 'Andy', 50, 3 ) ]
)
]
);
may also be written like this:
my $table = $h->stringify(
[
\'table',
[
\'tr',
[ \'th', 'Name', 'Score', 'Position' ],
[ \'td', 'Therese', 90, 1 ],
[ \'td', 'Chrissie', 85, 2 ],
[ \'td', 'Andy', 50, 3 ]
]
]
);
Any reference to an array whose first element is a reference to a scalar
[ \'methodname', args ]
is executed as a call to the named method with the specified args. iykyk. π
π Methods named after tags π
In addition to the methods described above, HTML::Tiny provides all of the following HTML generation methods:
a abbr acronym address applet area article aside audio b base bdi bdo big
blink blockquote body br button canvas caption center cite code col colgroup
data datalist dd del details dfn dialog dir div dl dt em embed fieldset
figcaption figure font footer form frame frameset h1 h2 h3 h4 h5 h6 head
header hgroup hr html i iframe img input ins kbd keygen label legend li link
main map mark marquee menu menuitem meta meter nav nobr noframes noscript
object ol optgroup option output p param picture portal pre progress q rb rp
rt rtc ruby s samp script section select slot small source spacer span strike
strong style sub summary sup table tbody td template textarea tfoot th thead
time title tr track tt u ul var video wbr xmp
The following methods generate closed XHTML (<br />) tags by default:
area base br col embed frame hr iframe img input keygen link meta param
source track wbr
So:
print $h->br; # prints <br />
print $h->input({ name => 'field1' });
# prints <input name="field1" />
print $h->img({ src => 'pic.jpg' });
# prints <img src="pic.jpg" />
All other tag methods generate tags to wrap whatever content they are passed:
print $h->p('Hello, World');
prints:
<p>Hello, World</p>
So the following are equivalent:
print $h->a({ href => 'http://hexten.net' }, 'Hexten');
and
print $h->tag('a', { href => 'http://hexten.net' }, 'Hexten');
same thing, two fits. slay. π
β¨ Utility Methods β¨
url_encode( $str )β URL-encodes a string, bestie. Spaces get turned into'+'and any character that isn't alphanumeric gets encoded as'%'followed by its hexadecimal character code. It's giving percent-encoding realness π
$h->url_encode( ' <hello> ' ) # returns '+%3chello%3e+'
url_decode( $str )β undoes all of that. Literally the reverse ofurl_encode. Slay, symmetry π¦
$h->url_decode( '+%3chello%3e+' ) # returns ' <hello> '
query_encode( $hash_ref )β takes an anonymous hash of key, value pairs and hands you back a query string. So:
print $h->query_encode({ a => 1, b => 2 })
would print
a=1&b=2
entity_encode( $str )β encodes the characters'<','>','&','\''and'"'as their HTML entity equivalents. Very demure, very mindful πΈ
print $h->entity_encode( '<>\'"&' );
would print:
<>'"&
json_encodeβ encodes a data structure in JSON (Javascript) format. Obsessed honestly:
print $h->json_encode( { ar => [ 1, 2, 3, { a => 1, b => 2 } ] } );
would print:
{"ar":[1,2,3,{"a":1,"b":2}]}
Because JSON is valid Javascript, this method can be useful when generating ad-hoc Javascript. For example:
my $some_perl_data = {
score => 45,
name => 'Fred',
history => [ 32, 37, 41, 45 ]
};
# Transfer value to Javascript
print $h->script( { type => 'text/javascript' },
"\nvar someVar = " . $h->json_encode( $some_perl_data ) . ";\n " );
# Prints
# <script type="text/javascript">
# var someVar = {"history":[32,37,41,45],"name":"Fred","score":45};
# </script>
Okay so important: if you attempt to json encode a blessed object,json_encodewill look for aTO_JSONmethod and, if found, use its return value as the structure to be converted in place of the object. And an attempt to encode a blessed object that does not implementTO_JSONwill fail. No cap. π
𧬠Subclassing π§¬
An HTML::Tiny is a blessed hash ref. That's it, that's the lore β¨
validate_tag( $closed, $name, $attr )β subclassvalidate_tagto throw an error or issue a warning when an attempt is made to generate an invalid tag. Your moment to be the main character who keeps everyone in line π
π AUTHOR π
Andy Armstrong <andy@hexten.net>
Aristotle Pagaltzis <pagaltzis@gmx.de>
π COPYRIGHT AND LICENSE π
This software is copyright (c) 2008 by Andy Armstrong.
This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
And that's the whole page, bestie! π This tea was served up by perl v5.36.0 on 2022-10-13 β go forth and generate some iconic markup, ily π«Άπβ
π¦ where this page comes from
- ubuntu noble: libhtml-tiny-perl 1.08-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libhtml-tiny-perl 1.08-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libhtml-tiny-perl 1.08-2 Β· 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