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.

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() }}
| improve this answer | |
  • Nice one! thanks for the clarification and tip :) – Alec Ritson Feb 1 '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 1 '16 at 18:29
  • @RitterKnight I concur, also curious about the use case here :) – Mats Mikkel Rummelhoff Feb 1 '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 7:02
4

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.

| improve this answer | |

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.