Search code examples
htmlperlcgitemplate-toolkit

Generating HTML dynamically in modern Perl web frameworks


What is the "modern Perl" recommended way to generate HTML dynamically?

I used to be able to just use CGI::tag ( @attr ), but seems this is deprecated now. However, reading through CGI::Alternatives, I only see examples using static HTML.

I suppose under Template::Toolkit, I would use something like [% html %], but that still leaves the problem of generating the corresponding $html string. I'm looking for a library, like CGI, that generates correct HTML tags, with correct escaping, knows about self-closing tags, etc, and is not being deprecated ... unless there is a way of doing things in modern Perl web frameworks that supersedes this altogether.

EDIT:

Some examples:

  • How do I generate the HTML for a dropdown (<select>) when the values and labels are only known at run-time? The CGI method was just 1 line: $q->popup_menu ({ name => $name, values => \@values, labels => \%labels }); The Template::Toolkit method involves so many lines of code (here is an example) ... isn't there another way?
  • How do I generate the HTML for a tag whose attributes are not known until run-time? In CGI it's just $q->tag ( \%attr ); ... what is the Template::Toolkit equivalent?
  • How do I generate HTML when a list of tags and their content is not known until run-time? In CGI it's: $q->parent ( \%attr, @child ); ... how is this done in Template::Toolkit? I realize this is kind of vague, but I deal with situations where large amounts of content are not known until run-time, so coming up with a template in advance seems untenable to me, but I may not be aware of some advanced features of Template::Toolkit.
  • I have more complicated cases to deal with as well, such as involving recursion, but if I get the above sorted out, then the rest might fall into place.

Solution

  • Personally, I'd build the HTML in the template in the same way as the <select> example that you give. The idea is that by separating it out into template that only contain HTML and a small amount of TT code, then it becomes easier for a front-end developer to edit the code without having to know Perl. And I really don't think it's as complex as you make it out to be:

    <select name="[% select.name %]">
    [% FOREACH option IN select.options -%]
      <option value="[% option.value %]">[% option.text %]</option>
    [% END -%]
    </select>
    

    But I also hear people talking about libraries like HTML::FormFu. Something like that might be what you're looking for.

    Update: Got bored at lunch and wrote a tag/attribute example:

    <tag [% FOREACH p IN attr.pairs; p.key %]="[% p.value %]" [% END %]>
    

    (Assumes that attr is a hash of attribute names and values).

    Which got me thinking that writing a library of these TT macros really wouldn't be hard.