Home > front end >  How to prevent Perl CGI->start_html() from printing DOCTYPE header
How to prevent Perl CGI->start_html() from printing DOCTYPE header

Time:03-06

when using Perl CGI, it always print out the: <"DOCTYPE html ".... > header before printing out the rest of the html body, which messes up the proper display of the web page. I guess the cause is the DOCTYPE still references a very old version of HTML. This first line get generated regardless when I use $query->start_html(...);. So the question is, how to prevent that <!DOCTYPE...> line from being generated? When I delete that DOCTYPE line, my web page runs properly after that. Any insight is greatly appreciated. Thanks!

CodePudding user response:

Browsers will use the DOCTYPE definition to decide whether or not to interpret an HTML (or XHTML) document in Quirks mode. I assume that's what you mean by "messes up the proper display of the web page" - you're carefully creating valid HTML5 but the browser goes into Quirks mode and the page doesn't look right.

What you want is the standard HTML DOCTYPE definition.

<!DOCTYPE html>

Unfortunately for you, the HTML generation functions in CGI.pm are unmaintained and don't have support for HTML5. So you can't get the module to generate this DOCTYPE.

Honestly, your best approach is to stop using all of the HTML generation functions and switch to a template-based approach instead. But I can see how that would be a big job so, in the short term, perhaps you can just stop using start_html(). It shouldn't be too hard to replace the call with a heredoc that contains the text that you want.

Update: The comment from Quentin below got me thinking. When I said:

you're carefully creating valid HTML5 but the browser goes into Quirks mode and the page doesn't look right

I was completely wrong. If you get the browser behaviour you want without a DOCTYPE, then you want to put the browser into Quirks mode. And that's far easier. Using the information from the Wikipedia article I linked to above, you can see that HTML 4.01 Transitional is the most recent DOCTYPE that will put all modern browsers into Quirks mode. So you can use that DOCTYPE.

$ perl -MCGI=:html -E'say start_html(-dtd => "-//W3C//DTD HTML 4.01 Transitional//EN")'
<!DOCTYPE html
        PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><title>Untitled Document</title>
</head>
<body>

And that should get the browsers working as you want them.

But relying on Quirks mode is fragile. I recommend that you consider fixing your HTML and CSS so that they work as you want when browsers are in Standards mode.

  • Related