How to load jinja template directly from filesystem

Here’s how: use a FileSystemLoader instead of a PackageLoader. I found examples on the web here and here. Let’s say you have a python file in the same dir as your template: ./index.py ./template.html This index.py will find the template and render it: #!/usr/bin/python import jinja2 templateLoader = jinja2.FileSystemLoader(searchpath=”./”) templateEnv = jinja2.Environment(loader=templateLoader) TEMPLATE_FILE = “template.html” … Read more

How can I pass data from Flask to JavaScript in a template?

You can use {{ variable }} anywhere in your template, not just in the HTML part. So this should work: <html> <head> <script> var someJavaScriptVar=”{{ geocode[1] }}”; </script> </head> <body> <p>Hello World</p> <button onclick=”alert(‘Geocode: {{ geocode[0] }} ‘ + someJavaScriptVar)” /> </body> </html> Think of it as a two-stage process: First, Jinja (the template engine … Read more

How do I format a date in Jinja2?

There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example {{ car.date_of_manufacture.strftime(‘%Y-%m-%d’) }} Another, sightly better approach would be to define your own filter, e.g.: from flask import Flask import babel app = Flask(__name__) @app.template_filter() def format_datetime(value, format=”medium”): if format … Read more

How to output loop.counter in python jinja template?

The counter variable inside the loop is called loop.index in Jinja2. >>> from jinja2 import Template >>> s = “{% for element in elements %}{{loop.index}} {% endfor %}” >>> Template(s).render(elements=[“a”, “b”, “c”, “d”]) 1 2 3 4 In addition to loop.index, there is also loop.index0 (index starting at 0) loop.revindex (reverse index; ending at 1) … Read more