Day 13. Using XHTML Strict mode during application development.

I have a confession to make:I hate HTML. I'm very bad at creating well formed markup, I hate validating it, and I really hate the annoying display bugs you find which are due to mis-matched tags.

Therefore a way to make my browser refuse to render my documents unless they were perfect HTML was very appealing, as it stops me from having to spend time fixing my awful markup at the end of a project, as it forces me to do it as I go along.

In this article I'm going to show you a simple CPAN module, Catalyst::View::TT::XHTML, which can be used during development to force your browser to strictly interpret XHTML.

I'm the paranoid sort, so I don't use this module in production, as, whilst I don't expect to generate invalid markup, I'd rather a client browser tried to render the page than it failed when not in development.

What does this module do?

The module is a very simple subclass of Catalyst::View::TT, which delegates to its parent for templating, and then, if the content type of the response is text/html, performs RFC2616 Content Negotiation with a strong preference for the application/xhtml+xml Content Type. If the client's Accept header supports this, it changes the content type to application/xhtml+xml, which causes browsers to turn on strict mode, ensuring that your XHTML is well formed.

This doesn't completely remove the need to validate your markup, but it does go a long way.

How do I use it?

Add the following code to MyApp/View/

    package MyApp::View::XHTML;
    use strict;
    use warnings;
    use base qw/Catalyst::View::TT::XHTML MyApp::View::TT/; 


Note that adding your current TT view to the right hand side of the inheritance causes the configuration from your normal TT view (assumed to be MyApp::View::TT in the example above) to be inherited, but Catalyst::View::XHTML needs to be on the left hand side so that its process method gets called first.

Then, assuming that you are using Catalyst::Action::RenderView, you can just set the default_view configuration parameter as appropriate to change the View.

Personally I configure the XHTML view in, but I have a commented-out entry setting it to the original TT view in myapp.conf, which I un-comment when my application is deployed.

That is kinda neat, but your module is only 5 lines of code..

Yes, it is.

And I had the same 5 lines of code in every application I'd ever written, with a conditional on the $c-debug> setting, quite often without the relevant Accept header checking.

Shortly after uploading this awful hack to CPAN, lots of people pointed out how much it sucked, sent me failing tests, and made suggestions, so the implementation is now much better than what I was using previously.



Tomas Doran (t0m) <>