1HTML::Tiny(3)         User Contributed Perl Documentation        HTML::Tiny(3)
2
3
4

NAME

6       HTML::Tiny - Lightweight, dependency free HTML/XML generation
7

VERSION

9       This document describes HTML::Tiny version 1.05
10

SYNOPSIS

12         use HTML::Tiny;
13
14         my $h = HTML::Tiny->new;
15
16         # Generate a simple page
17         print $h->html(
18           [
19             $h->head( $h->title( 'Sample page' ) ),
20             $h->body(
21               [
22                 $h->h1( { class => 'main' }, 'Sample page' ),
23                 $h->p( 'Hello, World', { class => 'detail' }, 'Second para' )
24               ]
25             )
26           ]
27         );
28
29         # Outputs
30         <html>
31           <head>
32             <title>Sample page</title>
33           </head>
34           <body>
35             <h1 class="main">Sample page</h1>
36             <p>Hello, World</p>
37             <p class="detail">Second para</p>
38           </body>
39         </html>
40

DESCRIPTION

42       "HTML::Tiny" is a simple, dependency free module for generating HTML
43       (and XML). It concentrates on generating syntactically correct XHTML
44       using a simple Perl notation.
45
46       In addition to the HTML generation functions utility functions are
47       provided to
48
49       •   encode and decode URL encoded strings
50
51       •   entity encode HTML
52
53       •   build query strings
54
55       •   JSON encode data structures
56

INTERFACE

58       "new"
59           Create a new "HTML::Tiny". The constructor takes one optional
60           argument: "mode". "mode" can be either 'xml' (default) or 'html'.
61           The difference is that in HTML mode, closed tags will not be closed
62           with a forward slash; instead, closed tags will be returned as
63           single open tags.
64
65           Example:
66
67             # Set HTML mode.
68             my $h = HTML::Tiny->new( mode => 'html' );
69
70             # The default is XML mode, but this can also be defined explicitly.
71             $h = HTML::Tiny->new( mode => 'xml' );
72
73           HTML is a dialect of SGML, and is not XML in any way. "Orphan" open
74           tags or unclosed tags are legal and in fact expected by user
75           agents. In practice, if you want to generate XML or XHTML, supply
76           no arguments. If you want valid HTML, use "mode => 'html'".
77
78   HTML Generation
79       "tag( $name, ... )"
80           Returns HTML (or XML) that encloses each of the arguments in the
81           specified tag. For example
82
83             print $h->tag('p', 'Hello', 'World');
84
85           would print
86
87             <p>Hello</p><p>World</p>
88
89           notice that each argument is individually wrapped in the specified
90           tag.  To avoid this multiple arguments can be grouped in an
91           anonymous array:
92
93             print $h->tag('p', ['Hello', 'World']);
94
95           would print
96
97             <p>HelloWorld</p>
98
99           The [ and ] can be thought of as grouping a number of arguments.
100
101           Attributes may be supplied by including an anonymous hash in the
102           argument list:
103
104             print $h->tag('p', { class => 'normal' }, 'Foo');
105
106           would print
107
108             <p class="normal">Foo</p>
109
110           Attribute values will be HTML entity encoded as necessary.
111
112           Multiple hashes may be supplied in which case they will be merged:
113
114             print $h->tag('p',
115               { class => 'normal' }, 'Bar',
116               { style => 'color: red' }, 'Bang!'
117             );
118
119           would print
120
121             <p class="normal">Bar</p><p class="normal" style="color: red">Bang!</p>
122
123           Notice that the class="normal" attribute is merged with the style
124           attribute for the second paragraph.
125
126           To remove an attribute set its value to undef:
127
128             print $h->tag('p',
129               { class => 'normal' }, 'Bar',
130               { class => undef }, 'Bang!'
131             );
132
133           would print
134
135             <p class="normal">Bar</p><p>Bang!</p>
136
137           An empty attribute - such as 'checked' in a checkbox can be encoded
138           by passing an empty array reference:
139
140             print $h->closed( 'input', { type => 'checkbox', checked => [] } );
141
142           would print
143
144             <input checked type="checkbox" />
145
146           Return Value
147
148           In a scalar context "tag" returns a string. In a list context it
149           returns an array each element of which corresponds to one of the
150           original arguments:
151
152             my @html = $h->tag('p', 'this', 'that');
153
154           would return
155
156             @html = (
157               '<p>this</p>',
158               '<p>that</p>'
159             );
160
161           That means that when you nest calls to tag (or the equivalent HTML
162           aliases - see below) the individual arguments to the inner call
163           will be tagged separately by each enclosing call. In practice this
164           means that
165
166             print $h->tag('p', $h->tag('b', 'Foo', 'Bar'));
167
168           would print
169
170             <p><b>Foo</b></p><p><b>Bar</b></p>
171
172           You can modify this behavior by grouping multiple args in an
173           anonymous array:
174
175             print $h->tag('p', [ $h->tag('b', 'Foo', 'Bar') ] );
176
177           would print
178
179             <p><b>Foo</b><b>Bar</b></p>
180
181           This behaviour is powerful but can take a little time to master. If
182           you imagine '[' and ']' preventing the propagation of the 'tag
183           individual items' behaviour it might help visualise how it works.
184
185           Here's an HTML table (using the tag-name convenience methods - see
186           below) that demonstrates it in more detail:
187
188             print $h->table(
189               [
190                 $h->tr(
191                   [ $h->th( 'Name', 'Score', 'Position' ) ],
192                   [ $h->td( 'Therese',  90, 1 ) ],
193                   [ $h->td( 'Chrissie', 85, 2 ) ],
194                   [ $h->td( 'Andy',     50, 3 ) ]
195                 )
196               ]
197             );
198
199           which would print the unformatted version of:
200
201               <table>
202                   <tr><th>Name</th><th>Score</th><th>Position</th></tr>
203                   <tr><td>Therese</td><td>90</td><td>1</td></tr>
204                   <tr><td>Chrissie</td><td>85</td><td>2</td></tr>
205                   <tr><td>Andy</td><td>50</td><td>3</td></tr>
206               </table>
207
208           Note how you don't need a td() for every cell or a tr() for every
209           row.  Notice also how the square brackets around the rows prevent
210           tr() from wrapping each individual cell.
211
212           Often when generating nested HTML you will find yourself writing
213           corresponding nested calls to HTML generation methods. The table
214           generation code above is an example of this.
215
216           If you prefer these nested method calls can be deferred like this:
217
218             print $h->table(
219               [
220                 \'tr',
221                 [ \'th', 'Name',     'Score', 'Position' ],
222                 [ \'td', 'Therese',  90,      1 ],
223                 [ \'td', 'Chrissie', 85,      2 ],
224                 [ \'td', 'Andy',     50,      3 ]
225               ]
226             );
227
228           In general a nested call like
229
230             $h->method( args )
231
232           may be rewritten like this
233
234             [ \'method', args ]
235
236           This allows complex HTML to be expressed as a pure data structure.
237           See the "stringify" method for more information.
238
239       "open( $name, ... )"
240           Generate an opening HTML or XML tag. For example:
241
242             print $h->open('marker');
243
244           would print
245
246             <marker>
247
248           Attributes can be provided in the form of anonymous hashes in the
249           same way as for "tag". For example:
250
251             print $h->open('marker', { lat => 57.0, lon => -2 });
252
253           would print
254
255             <marker lat="57.0" lon="-2">
256
257           As for "tag" multiple attribute hash references will be merged. The
258           example above could be written:
259
260             print $h->open('marker', { lat => 57.0 }, { lon => -2 });
261
262       "close( $name )"
263           Generate a closing HTML or XML tag. For example:
264
265             print $h->close('marker');
266
267           would print:
268
269             </marker>
270
271       "closed( $name, ... )"
272           Generate a closed HTML or XML tag. For example
273
274             print $h->closed('marker');
275
276           would print:
277
278             <marker />
279
280           As for "tag" and "open" attributes may be provided as hash
281           references:
282
283             print $h->closed('marker', { lat => 57.0 }, { lon => -2 });
284
285           would print:
286
287             <marker lat="57.0" lon="-2" />
288
289       "auto_tag( $name, ... )"
290           Calls either "tag" or "closed" based on built in rules for the tag.
291           Used internally to implement the tag-named methods.
292
293       "stringify( $obj )"
294           Called internally to obtain string representations of values.
295
296           It also implements the deferred method call notation (mentioned
297           above) so that
298
299             my $table = $h->table(
300               [
301                 $h->tr(
302                   [ $h->th( 'Name', 'Score', 'Position' ) ],
303                   [ $h->td( 'Therese',  90, 1 ) ],
304                   [ $h->td( 'Chrissie', 85, 2 ) ],
305                   [ $h->td( 'Andy',     50, 3 ) ]
306                 )
307               ]
308             );
309
310           may also be written like this:
311
312             my $table = $h->stringify(
313               [
314                 \'table',
315                 [
316                   \'tr',
317                   [ \'th', 'Name',     'Score', 'Position' ],
318                   [ \'td', 'Therese',  90,      1 ],
319                   [ \'td', 'Chrissie', 85,      2 ],
320                   [ \'td', 'Andy',     50,      3 ]
321                 ]
322               ]
323             );
324
325           Any reference to an array whose first element is a reference to a
326           scalar
327
328             [ \'methodname', args ]
329
330           is executed as a call to the named method with the specified args.
331
332   Methods named after tags
333       In addition to the methods described above "HTML::Tiny" provides all of
334       the following HTML generation methods:
335
336         a abbr acronym address area b base bdo big blockquote body br
337         button caption cite code col colgroup dd del div dfn dl dt em
338         fieldset form frame frameset h1 h2 h3 h4 h5 h6 head hr html i
339         iframe img input ins kbd label legend li link map meta noframes
340         noscript object ol optgroup option p param pre q samp script select
341         small span strong style sub sup table tbody td textarea tfoot th
342         thead title tr tt ul var
343
344       The following methods generate closed XHTML (<br />) tags by default:
345
346         area base br col frame hr img input meta param
347
348       So:
349
350         print $h->br;   # prints <br />
351         print $h->input({ name => 'field1' });
352                         # prints <input name="field1" />
353         print $h->img({ src => 'pic.jpg' });
354                         # prints <img src="pic.jpg" />
355
356       All other tag methods generate tags to wrap whatever content they are
357       passed:
358
359         print $h->p('Hello, World');
360
361       prints:
362
363         <p>Hello, World</p>
364
365       So the following are equivalent:
366
367         print $h->a({ href => 'http://hexten.net' }, 'Hexten');
368
369       and
370
371         print $h->tag('a', { href => 'http://hexten.net' }, 'Hexten');
372
373   Utility Methods
374       "url_encode( $str )"
375           URL encode a string. Spaces become '+' and non-alphanumeric
376           characters are encoded as '%' + their hexadecimal character code.
377
378             $h->url_encode( ' <hello> ' )   # returns '+%3chello%3e+'
379
380       "url_decode( $str )"
381           URL decode a string. Reverses the effect of "url_encode".
382
383             $h->url_decode( '+%3chello%3e+' )   # returns ' <hello> '
384
385       "query_encode( $hash_ref )"
386           Generate a query string from an anonymous hash of key, value pairs:
387
388             print $h->query_encode({ a => 1, b => 2 })
389
390           would print
391
392             a=1&b=2
393
394       "entity_encode( $str )"
395           Encode the characters '<', '>', '&', '\'' and '"' as their HTML
396           entity equivalents:
397
398             print $h->entity_encode( '<>\'"&' );
399
400           would print:
401
402             &lt;&gt;&apos;&quot;&amp;
403
404       "json_encode"
405           Encode a data structure in JSON (Javascript) format:
406
407             print $h->json_encode( { ar => [ 1, 2, 3, { a => 1, b => 2 } ] } );
408
409           would print:
410
411             {"ar":[1,2,3,{"a":1,"b":2}]}
412
413           Because JSON is valid Javascript this method can be useful when
414           generating ad-hoc Javascript. For example
415
416             my $some_perl_data = {
417               score   => 45,
418               name    => 'Fred',
419               history => [ 32, 37, 41, 45 ]
420             };
421
422             # Transfer value to Javascript
423             print $h->script( { type => 'text/javascript' },
424                 "\nvar someVar = " . $h->json_encode( $some_perl_data ) . ";\n " );
425
426             # Prints
427             # <script type="text/javascript">
428             # var someVar = {"history":[32,37,41,45],"name":"Fred","score":45};
429             # </script>
430
431           If you attempt to json encode a blessed object "json_encode" will
432           look for a "TO_JSON" method and, if found, use its return value as
433           the structure to be converted in place of the object. An attempt to
434           encode a blessed object that does not implement "TO_JSON" will
435           fail.
436
437   Subclassing
438       An "HTML::Tiny" is a blessed hash ref.
439
440       "validate_tag( $closed, $name, $attr )"
441           Subclass "validate_tag" to throw an error or issue a warning when
442           an attempt is made to generate an invalid tag.
443

CONFIGURATION AND ENVIRONMENT

445       HTML::Tiny requires no configuration files or environment variables.
446

DEPENDENCIES

448       By design HTML::Tiny has no non-core dependencies.
449
450       To run the tests you will require Test::More.
451

INCOMPATIBILITIES

453       None reported.
454

BUGS AND LIMITATIONS

456       No bugs have been reported.
457
458       Please report any bugs or feature requests to
459       "bug-html-tiny@rt.cpan.org", or through the web interface at
460       <http://rt.cpan.org>.
461

AUTHOR

463       Andy Armstrong  "<andy@hexten.net>"
464
465       Aristotle Pagaltzis "<pagaltzis@gmx.de>"
466
468       Copyright (c) 2008, Andy Armstrong "<andy@hexten.net>". All rights
469       reserved.
470
471       This module is free software; you can redistribute it and/or modify it
472       under the same terms as Perl itself. See perlartistic.
473

DISCLAIMER OF WARRANTY

475       BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
476       FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
477       WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
478       PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
479       EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
480       WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
481       ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
482       YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
483       NECESSARY SERVICING, REPAIR, OR CORRECTION.
484
485       IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
486       WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
487       REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
488       TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
489       CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
490       SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
491       RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
492       FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
493       SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
494       DAMAGES.
495
496
497
498perl v5.34.0                      2021-07-22                     HTML::Tiny(3)
Impressum