4

I need a nice way to determine whether I'm on a 200 page. Basically anything other than a status page (404, 500, 403) in twig templates.

I thought I could do something like craft.request.getStatus or craft.request.status but this didn't work.

From looking in the HttpRequestService.php file there doesn't seem to be anything to retrieve this info so I wondered if anyone has achieved something similar.

Alec Ritson
  • 4,529
  • 1
  • 19
  • 34

2 Answers2

8

Since this is the top hit in Google, I'll guess it's handy to mention that craft.app.response.statusCode will display the statuscode in Craft v3 and up.

NxWebster
  • 81
  • 1
  • 1
3

No, the craft.request (HttpRequestVariable) class doesn't expose the HTTP status code.

It'd be super easy to add it to Twig as a variable method in a custom plugin, though:

namespace Craft;

class MyPluginVariable {

    public function getHttpStatus()
    {
        return http_response_code(); 
    }

}

...and in your template:

{{ craft.myPlugin.getHttpStatus() }}
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69
  • Nice one! thanks for the clarification and tip :) – Alec Ritson Feb 01 '16 at 14:37
  • Good answer though not sure why this is actually necessary in practice? If the request gets to Twig, it's either going to be 200 or an error that Craft intercepts and passes along (404, 500, 403) in which case you could just load the appropriate template... eg 404.html, 503.html, etc – RitterKnight Feb 01 '16 at 18:29
  • @RitterKnight I concur, also curious about the use case here :) – Mats Mikkel Rummelhoff Feb 01 '16 at 18:30
  • The use case was to build a plugin which detects the status code and if it's a 500 or 404 or whatever would ping an email to the system admin with details so you could display a "something went wrong but we have been notified" kinda thing :) – Alec Ritson Feb 26 '16 at 07:02