Share Jinja2 Templates with the Browser using Nunjucks
February 9, 2014
The setup for sharing jinja2 templates in the browser is fairly simple. It should take less than 10 minutes in a brand new project. Just follow the steps below and you should be up and running in no time.
Serve Templates to the Client
Flask by default serves things in the static folder. Add a folder
templates so that nunjucks can load them over HTTP/HTTPS.
Flask and jinja2 are paired nicely and the configuration is simple. Below is two different approaches to setting up jinja2. Flask app’s have a
jinja_loader property that can be used to setup the way jinja loads its templates. Either of the two approaches below will allow you to use the regular flask rendering methods.
render_template will function just as expected.
All Templates Served to the Client
Use Shared Templates and Server-Side Templates
Download nunjucks from the homepage. There are a few different variants, for starting out I recommend the full version. In the future you should read about precompiled templates, and the recommended setups for production.
Nunjucks is simple and will run as long as you tell it where to load the templates. Simply make a call to
nunjucks.compile. In your js file add the following line.
After the simple configuration you can make a call to
nunjucks.render to render a template in the browser.