The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Valiant::HTML::TagBuilder - Safely build HTML tags

SYNOPSIS

  use Valiant::HTML::TagBuilder ':all';

DESCRIPTION

Protecting your templates from the various types of character injection attacks is a prime concern for anyone working with the HTML user interface. This class provides some methods and exports to make this job easier.

EXPORTABLE FUNCTIONS

The following functions can be exported by this library:

tag

  tag $name;
  tag $name, \%attrs;

Returns an instance of Valiant::HTML::SafeString which is representing an html tag. Example:

  tag 'hr';                               # <hr/>
  tag img => +{src=>'/images/photo.jpg'}; # <img src='/images/photo.jpg' />

Generally \%attrs should be a list of key / values where a value is a plain scalar; However data-* and aria-* attributes can be set with a single data or aria key pointing to a hash of sub-attributes. Example:

  tag article => { id=>'main', data=>+{ user_id=>100 } };

Renders as:

  <article id='main', data-user-id='100' />

Note that underscores in the data-* or aria-* sub hashref keys are converted to '-' for rendering.

content_tag

  content_tag $name, \%attrs, \&block;
  content_tag $name, \&block;
  content_tag $name, $content, \%attrs;
  content_tag $name, $content;

Returns an instance of Valiant::HTML::SafeString which is representing an html tag with content. Content will be escaped via Valiant::HTML::SafeString's safe function (unless already marked safe by the user. Example:

  content_tag 'a', 'the link', +{href=>'a.html'}; # <a href="a.html">the link</a>;
  content_tag div => sub { 'The Lurker Above' };  # <div>The Lurker Above</div>

For the block version of thie function, the coderef is permitted to return an array of strings all of which we processed for safeness and finally everything will be concatenated into a single string encapulated by Valiant::HTML::SafeString.

capture

  capture \&block;
  capture \&block, @args;

Returns a Valiant::HTML::SafeString encapsulated string which is the return value (or array of values) returned by block. Any additional arguments passed to the function will be passed to the coderef at execution time. Useful when you need to have some custom logic in your tag building code. Example:

    capture sub {
      if(shift) {
        return content_tag 'a', +{ href=>'profile.html' };
      } else {
        return content_tag 'a', +{ href=>'login.html' };
      }
    }, 1;

Would return:

    <a href="profile.html">Profile</a>

SEE ALSO

Valiant, Valiant::HTML::FormBuilder

AUTHOR

See Valiant

COPYRIGHT & LICENSE

See Valiant