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