AlarmClockMan
AlarmClockMan

Reputation: 458

Import python modules to a Flask header file with jinja

Say I have this header.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Title</title>
</head>
<body>
    {{ random.randrange(0, 5) }}
    {% block body %}
        
    {% endblock %}
</body>
</html>

and this main.html file which extends it:

{% extends "header.html" %}

{% block body %}
    <p>Hello</p>
{% endblock %}

and this main.py file:

from flask import Flask, render_template
import random

app = Flask(__name__)

@app.route("/")
def main():
    return render_template("main.html")

app.run()

Currently when I run this and go to the website it shows a 500 Internal Server Error and I get this error in my python console:

jinja2.exceptions.UndefinedError: 'random' is undefined

How could I be able to somehow 'import' the random library into the header.html template?

I am running

Upvotes: 2

Views: 2102

Answers (2)

yuxiaoy
yuxiaoy

Reputation: 244

Actually you can use decorator app.context_processor to achieve that:

import os
import random


@app.context_processor
def handle_context():
    '''Inject object into jinja2 templates.'''
    return dict(os=os, random=random)

Then you can use os, random in your each template without input them in your view function:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ random.randint(0,10) }}<br>
{{ os.path.abspath('') }}
</body>
</html>

You would get something like this:

6
F:\Python\MyProject

Upvotes: 2

GAEfan
GAEfan

Reputation: 11360

Jinja doesn't recognize random. That is python which has to be imported, therefore not jinja built-in. Jinja has a built-in random filter:

{{ range(5)|random }} 

Update for second part of question:

You can create your own filters using python. Example (using Flask):

@app.template_filter('datetimeformat')
def datetimeformat(value, format="%Y-%m-%d %H:%M:%S"):
    return value.strftime(format)


{{ the_date|datetimeformat("%Y-%m-%d") }}

Upvotes: 3

Related Questions