Skip to content

How to render a custom template for 403 page #2209

@usr345

Description

@usr345

Here is a minimal working example:

use Mojolicious::Lite;

# Adding a custom condition
app->routes->add_condition(auth => sub {
    my ($route, $c, $captures, $num) = @_;

    $c->res->code(403);
    $c->rendered(403);
    # Here, you could define your condition. For example, check if a parameter is set.
    return 0;  # true/false depending on parameter
});

my $r = app->routes;
$r->get('/block')->requires(auth => 1)->to(cb => sub {
  my $c = shift;
  $c->render(template => 'default');
});

# Route for home
get '/' => sub {
    my $c = shift;
    $c->render(template => 'main');
};

# Default template
app->start;

__DATA__

@@ 403.html.ep
<!DOCTYPE html>
<html>
<head><title>Default Template</title></head>
<body>
<h1>Welcome to the Default Template</h1>
<p>This is the default template.</p>
</body>
</html>

@@ main.html.ep
<!DOCTYPE html>
<html>
<head><title>Main page</title></head>
<body>
<h1>Welcome to the main page</h1>
<p>The main page is here.</p>
</body>
</html>
  • [http://127.0.0.1:3000/block](http://127.0.0.1:3000/block) - gives an empty page with 403 status code
    
  • [http://127.0.0.1:3000/](http://127.0.0.1:3000/) - gives the main page rendered.
    

What should I do to use a custom template for 403 page?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions