Search code examples
pythonerror-handlinghttp-status-code-404jinja2bottle

How to deliver custom HTML on a bottle 404 Handler?


I'm trying to use the jinja2_view plugin to render a template from a custom error handler like this:

from bottle import Bottle, abort, jinja2_view

app = Bottle()

@jinja2_view('index.html')
@app.get('/')
def index():
    abort(404)

@jinja_view('404.html')
@app.error(404)
def handle404(error):
    return error

But this doesn't work.

I tried returning a string from the handler like this:

from bottle import Bottle, abort, jinja2_view

app = Bottle()

@jinja2_view('index.html')
@app.get('/')
def index():
    abort(404)


@app.error(404)
def handle404(error):
    return '<h1>Custom code</h1>'

It worked, but it's not the preferred option.

How i can make this work?


Solution

  • You can always instantiate your own Jinja Environment like this:

    from bottle import Bottle, abort, jinja2_view
    from jinja2 import Environment, PackageLoader
    
    env = Environment(loader=PackageLoader('yourapplication', 'templates'))
    
    app = Bottle()
    
    @jinja2_view('index.html')
    @app.get('/')
    def index():
        abort(404)
    
    
    @app.error(404)
    def handle404(error):
        template = env.get_template('404.html')
        return template.render()
    

    The bad thing about this aproach is that all the configuration made on the bottle jinja plugin is lost and you have to configure this again.

    Good news is that there is another jinja plugin available in bottle, named jinja2_template, that is not to be annotated, but to be returned in the request.

    from bottle import Bottle, abort, jinja2_view, jinja2_template
    
    app = Bottle()
    
    @jinja2_view('index.html')
    @app.get('/')
    def index():
        abort(404)
    
    
    @app.error(404)
    def handle404(error):
        return jinja2_template('404.html')
    

    So if you can change the code to this you can load the template from jinja correctly, using the same configurations from the bottle jinja plugin.