Chankey Pathak Chankey Pathak - 1 year ago 58
Perl Question

Using HTML::Template to add a tag

I'm using CGI and HTML::Template. I need to add below tag in all the templates which contain

tag (tag should be added inside

<input type="hidden" value="TO_BE_PARSED_FROM_CGI">

I don't want to edit all the template files manually. Is there any method available in HTML::Template to do this? Some type of hook which I can pass while creating constructor of HTML::Template?

Answer Source

You don't have to modify all the template files manually. Perl has HTML parsers that can help you locate where the changes need to be made. Go ahead and fix the templates once as opposed to modifying your code to do it each and every time it runs. Below, I use \*DATA for illustrative purposes, but, clearly, the list of template files could come from anywhere.

Back the files up first (better still, make sure you do this in a branch in your version control system).

#!/usr/bin/env perl

use utf8;
use strict;
use warnings;
use open qw[ :std :encoding(UTF-8) ];

use HTML::TokeParser::Simple;


sub run {
    my $argv = shift;
    my $parser = HTML::TokeParser::Simple->new(handle => \*DATA);

    while (my $token = $parser->get_token) {
        print $token->as_is;
        if ($token->is_start_tag('form')) {
            print qq{\n<input type="hidden" name="sid" value="<TMPL_VAR NAME=SID>">\n};

<h3>Here is a form:</h3>


<label for="date">Date:</label>
<input type="date" name="date" id="date">

<input type="submit">