User Agent Viewtool

Last Updated: Aug 20, 2021
documentation for the dotCMS Content Management System

The User AgentTool is a viewtool for getting user agent information from within Velocity code. It provides methods to get information about the user agent, device type, browser, browser version, operating system, manufacturer and rendering engine. These can be used to display different versions of content depending on the user's platform.

Credit

This viewtool calls libraries from the user-agent-utils project by Harold Walker.

Usage

Components of the User Agent information can be retrieved as follows:

User Agent InformationVelocity CodeExample Result
Agent$useragent.agentWINDOWS_7-CHROME45
Device type$useragent.typeCOMPUTER
Browser$useragent.browserCHROME45
Browser version$useragent.version45.0.2454.99
Operating System$useragent.osWINDOWS_7
Manufacturer$useragent.manufacturerMICROSOFT
Rendering engine$useragent.engineWEBKIT

Examples

These examples demonstrate two of the most common uses of the User Agent Viewtool.

Example 1: Display Platform Information

The following velocity code displays all platform information available from the User Agent Tool.

<pre>
Agent:        $useragent.agent
Type:         $useragent.type
Browser:      $useragent.browser
Version:      $useragent.version
OS:           $useragent.os
Manufacturer: $useragent.manufacturer
Engine:       $useragent.engine
</pre>

Which displays the following on a sample test system:

Agent:        WINDOWS_7-CHROME45
Type:         COMPUTER
Browser:      CHROME45
Version:      45.0.2454.99
OS:           WINDOWS_7
Manufacturer: MICROSOFT
Engine:       WEBKIT

Example 2: Change How Images are Displayed on Different Platforms

The following velocity code resizes the displayed image to a width appropriate for the platform where the page is viewed.

#if("$!{useragent.type}" == "MOBILE")
    #set("$image_width" = "250")
#elseif("$!{useragent.type}" == "TABLET")
    #set("$image_width" = "400")
#else
    #set("$image_width" = "600")
#end  
<img src="/dA/c3d0ab93-cee9-4ed3-849d-2132701e6b0c/fileAsset/filter/Resize/resize_w/$!{image_width}/" />  

Toolbox.xml Configuration

The following example shows how the User AgentTool is mapped in the toolbox.xml file:

    <tool>
        <key>useragent</key>
        <scope>request</scope>
        <class>com.dotcms.rendering.velocity.viewtools.UserAgentTool</class>
    </tool>

On this page

×

We Dig Feedback

Selected excerpt:

×