Question

Is there a way to detect what browser you are using through template toolkit? For example I can achieve what I want to do using jQuery but thought it would be useful to know how to do it in template toolkit if possible?

Jquery

    <script>
    jQuery(window).load(function(){
        if ( (jQuery.browser.msie && jQuery.browser.version < 9.0) )
        {
            jQuery('body').addClass('old-ie');
        }
    });
    </script>

In template toolkit I want to do something like the below but can't see this in the documentation anywhere?

    <body 
    [% IF browser.msie && browser.version < 9.0 %]
    class="old-ie"
    [% ELSE %]
    [% END %]
    >
Was it helpful?

Solution

I'm not aware of a TT plug-in for this, but it's trivial to add a line or two to your back-end application to make the information available to the template. For example, if your app is Catalyst based, you would add something like this to your main program:

__PACKAGE__->apply_request_class_roles(qw/
    Catalyst::TraitFor::Request::BrowserDetect
/);

... and in your 'auto' handler, introduce a line such as (untested):

$c->stash(browser => $c->req->browser);

... or just use this is your template:

[%- SET browser = c.req.browser;
    SET old_ie = 'class="old-ie"'
        IF browser.windows && browser.ie && browser.public_major < 9.0;
-%]

and then include old_ie wherever it's required in your template.

See Catalyst::TraitFor::Request::BrowserDetect and HTTP::BrowserDetect for more info and options. I'm sure there are similar plugins/methods for Dancer, Mojolicious etc.

OTHER TIPS

You could do that through the HTTP request headers. You didn't mention what was calling TT, but if you're using Catalyst, you could use Catalyst::TraitFor::Request::BrowserDetect, and then pass a variable to TT to say what kind of browser was requesting the page.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top