3

I would like to detect if a header in the current request is present and obtain its value, directly within a Twig template. I know that craft.app.request gives access to a few variables like isAjax that directly check the headers content, but I haven't found a method to directly retrieve a specific header.

Can this be achieved in some way? (preferably not by writing a plugin)

2 Answers 2

4

By checking the code, I could find a method named getHeaders() that will return all the headers of the current request.

So if you want to retrieve the content of the foo header, just use:

{% set headers = craft.app.request.getHeaders() %}
{% set fooHeader = headers['foo'] %}
1
  • 2
    Worth noting that attempting to access the headers variable as an array will result in a Twig Runtime Error, specifically Key "foo" in object with ArrayAccess of class "yii\web\HeaderCollection" does not exist.. Using the get method for the HeaderCollection is recommend, as follows, {{ headers.get('foo') }}
    – zesda
    Commented Oct 10, 2018 at 13:48
2

craft.app.request.getHeaders() returns an instance of yii\web\HeaderCollection, which has a number of public methods you can use from a Twig template.

For example, to see if an isAjax header is present:

{# Get the header collection #}
{% set headers = craft.app.request.getHeaders() %}

{# Test for specific header #}
{% set isAjaxRequest = headers.has('isAjax') %}

{% if isAjaxRequest %}
  {# Do something... #}
{% endif %}

If you need to read the value of a header, use the get() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.