Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enable autoescaping in templates with a .jhtml extension in Flask?

The Flask docs state:

autoescaping is enabled for all templates ending in .html, .htm, .xml as well as .xhtml

How do I enable autoescaping for templates ending with a .jhtml extension?

like image 626
Charles Roper Avatar asked Dec 20 '22 14:12

Charles Roper


2 Answers

It looks like you can set the file extensions with the 'autoescape' option when creating the app. Take a look at the create_jinja_environment() method at https://github.com/mitsuhiko/flask/blob/master/flask/app.py

like image 105
Brian Cajes Avatar answered Feb 03 '23 10:02

Brian Cajes


Thanks to @Cagez's answer I was able to come up with a robust (and recommended) solution.

According to a post on the Flask mailing list, the way to do this is to override flask.Flask.select_jinja_autoescape(). The linked snippet in that post demonstrating how to override which templates are autoescaped didn't quite work, so I came up with the following, which does work:

class JHtmlEscapingFlask(Flask):

    def select_jinja_autoescape(self, filename):
        if filename is None:
            return False
        if filename.endswith('.jhtml'):
            return True
        return Flask.select_jinja_autoescape(self, filename)

app = JHtmlEscapingFlask(__name__)

I put this at the top of my main Flask app file, replacing the usual app = Flask(__name__)

like image 35
Charles Roper Avatar answered Feb 03 '23 11:02

Charles Roper