Search code examples
perlcgiperl-html-template

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 <form> tag (tag should be added inside <form> tag).

<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?


Solution

  • 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;
    
    run(\@ARGV);
    
    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};
            }
        }
    }
    
    __DATA__
    <h3>Here is a form:</h3>
    
    <form
        method="POST"
        action="https://example.com/action-action-action.pl"
        id="action"
        name="actionable_form">
    
    <label for="date">Date:</label>
    <input type="date" name="date" id="date">
    
    <input type="submit">
    
    </form>