Reputation: 3
I have an assignment to construct a simple webpage with flask. I've gotten it working and have everything I need so far in my templates. What I can't figure out is how to display the date time on my pages. Do I put the date time in the templates individually, or put it in the base python code? My instructions say to just use the standard python date time function. But it isn't displaying when i test my page.
from flask import Flask
from flask import render_template
import datetime
app = Flask(__name__)
@app.route('/')
def index():
return show_home()
def show_home():
return render_template('index.html')
@app.route('/ingredients/')
def ingredients():
return show_ingredients()
def show_ingredients():
return render_template('ingredients.html')
@app.route('/cooking_instructions/')
def cook_it():
return show_cook_it()
def show_cook_it():
return render_template('cooking_instructions.html')
Upvotes: 0
Views: 4979
Reputation: 1228
You can just pass the string representation of the datetime into the render_template
function like so:
from datetime import datetime
@app.route('/example')
def example():
return render_template('template.html', datetime = str(datetime.now()))
You can then access the variable in your template using the syntax {{ datetime }}
. Of course you can customize how your datetime will look in your template by using the strftime
method on your datetime object.
This will not be dynamic, so once the template renders the datetime will not update. If you are looking for a counting clock you need to write that code in javascript. Check out this example HTML Display Current date
Upvotes: 3