Main Python File
Here is the common app.py file that interfaces with all the HTML files.
Python3
from flask import Flask, render_template, redirect, url_for app = Flask(__name__) @app .route( "/" ) def home(): return render_template( "index.html" ) @app .route( "/default" ) def default(): return render_template( "layout.html" ) @app .route( "/variable" ) def var(): user = "w3wiki" return render_template( "variable_example.html" , name = user) @app .route( "/if" ) def ifelse(): user = "Practice w3wiki" return render_template( "if_example.html" , name = user) @app .route( "/for" ) def for_loop(): list_of_courses = [ 'Java' , 'Python' , 'C++' , 'MATLAB' ] return render_template( "for_example.html" , courses = list_of_courses) @app .route( "/choice/<pick>" ) def choice(pick): if pick = = 'variable' : return redirect(url_for( 'var' )) if pick = = 'if' : return redirect(url_for( 'ifelse' )) if pick = = 'for' : return redirect(url_for( 'for_loop' )) if __name__ = = "__main__" : app.run(debug = False ) |
Templating With Jinja2 in Flask
Flask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support named Jinja2. Jinja2 is one of the most used Web template engines for Python. This Web template engine is a fast, expressive, extensible templating engine. Jinja2 extensively helps to write Python code within the HTML file. Further, it also includes:
- Async support for generating templates that automatically handle sync and async functions without extra syntax.
- Template inheritance and inclusion.
- The Template engine makes debugging easier.
- Support of both High-level and Low-level API support.
Install the required package
To install the Jinja2 package in Python, check your latest pip version and stay updated. Install Jinja2 using the following command:
pip install Jinja2
But since we are dealing with the Templating with Jinja2 in Flask, there is no need to separately install Jinja2. When you install the Flask framework, the Jinja2 comes installed with it.
pip install flask
Contact Us