Referencing HTTP headers in a Freemarker template

This article explains how to access HTTP headers from within a Freemarker template.

The data model includes a hidden httpRequest object that can be referenced from with Freemarker templates.

Example: Print all the HTTP headers

The following code prints out (inside HTML comments) the HTTP request headers to assist with debugging.

Freemarker template (e.g. simple.ftl)

<#assign headers=httpRequest.getHeaderNames()>

<#list headers as header>
<#assign hval=httpRequest.getHeader(header)>
'${header}': '${hval}'

Example: Use a header to switch what’s displayed

The following code reads a custom http header attribute (X-Funnelback-form) and uses this as a condition within an if statement:

Freemarker template (e.g. simple.ftl)
<#ftl encoding="utf-8" />
<#import "/web/templates/modernui/funnelback_classic.ftl" as s/>
<#import "/web/templates/modernui/funnelback.ftl" as fb/>
<html lang="en">
         <#assign  mtype=httpRequest.getHeader('X-Funnelback-form')>
         <#if mtype == "mobile">
             <#include "simple-mobile.ftl">
             <#include "simple-basic.ftl">