2

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)

3

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
    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 Oct 10 '18 at 13:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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