HTML-Tiny
view release on metacpan or search on metacpan
lib/HTML/Tiny.pm view on Meta::CPAN
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
) ) {
no strict 'refs';
*$tag = sub { shift->auto_tag( $tag, @_ ) };
}
}
# Tags that are closed (<br /> versus <br></br>)
my @DEFAULT_CLOSED
# https://developer.mozilla.org/en-US/docs/Glossary/Empty_element
= qw( area base br col embed hr img input keygen link meta param source track wbr );
# Tags that get a trailing newline
my @DEFAULT_NEWLINE = qw( html head body div p tr table );
my %DEFAULT_AUTO = (
suffix => '',
method => 'tag'
);
=head1 SYNOPSIS
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>
=head1 DESCRIPTION
C<< HTML::Tiny >> is a simple, dependency free module for generating
HTML (and XML). It concentrates on generating syntactically correct
XHTML using a simple Perl notation.
In addition to the HTML generation functions utility functions are
provided to
=over
=item * encode and decode URL encoded strings
=item * entity encode HTML
=item * build query strings
=item * JSON encode data structures
=back
=head1 INTERFACE
=over
=item C<< new >>
Create a new C<< HTML::Tiny >>. The constructor takes one optional
argument: C<< mode >>. C<< mode >> can be either C<< 'xml' >> (default)
or C<< 'html' >>. The difference is that in HTML mode, closed tags will
not be closed with a forward slash; instead, closed tags will be
returned as single open tags.
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' );
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. In
practice, if you want to generate XML or XHTML, supply no arguments. If
you want valid HTML, use C<< mode => 'html' >>.
=back
=cut
sub new {
my $self = bless {}, shift;
my %params = @_;
my $mode = $params{'mode'} || 'xml';
croak "Unknown mode: $mode"
unless $mode eq 'xml'
or $mode eq 'html';
$self->{'_mode'} = $mode;
$self->_set_auto( 'method', 'closed', @DEFAULT_CLOSED );
$self->_set_auto( 'suffix', "\n", @DEFAULT_NEWLINE );
return $self;
lib/HTML/Tiny.pm view on Meta::CPAN
[
\'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.
=cut
sub stringify {
my ( $self, $obj ) = @_;
if ( ref $obj ) {
# Flatten array refs...
if ( 'ARRAY' eq ref $obj ) {
# Check for deferred method call specified as a scalar
# ref...
if ( @$obj && 'SCALAR' eq ref $obj->[0] ) {
my ( $method, @args ) = @$obj;
return join '', $self->$$method( @args );
}
return join '', map { $self->stringify( $_ ) } @$obj;
}
# ...stringify objects...
my $str;
return $str if eval { $str = $obj->as_string; 1 };
}
# ...default stringification
return "$obj";
}
=back
=head2 Methods named after tags
In addition to the methods described above C<< 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');
=head2 Utility Methods
=over
=item C<< url_encode( $str ) >>
URL encode a string. Spaces become '+' and non-alphanumeric characters
are encoded as '%' + their hexadecimal character code.
$h->url_encode( ' <hello> ' ) # returns '+%3chello%3e+'
=cut
sub url_encode {
my $str = $_[0]->stringify( $_[1] );
$str
=~ s/([^A-Za-z0-9_~])/$1 eq ' ' ? '+' : sprintf("%%%02x", ord($1))/eg;
return $str;
}
=item C<< url_decode( $str ) >>
URL decode a string. Reverses the effect of C<< url_encode >>.
$h->url_decode( '+%3chello%3e+' ) # returns ' <hello> '
=cut
sub url_decode {
my $str = $_[1];
$str =~ s/[+]/ /g;
( run in 1.397 second using v1.01-cache-2.11-cpan-119454b85a5 )