0% found this document useful (0 votes)
25 views20 pages

Flask Templates and Static Files Guide

This document provides a beginner-friendly guide to using Templates and Static Files in Flask, explaining the roles of HTML templates and static files like CSS and JavaScript. It covers the Jinja2 template engine, demonstrating how to use variables, loops, and conditions within templates, as well as the importance of a structured folder layout for organizing templates and static files. The document also includes practical examples and analogies to illustrate concepts clearly.

Uploaded by

billiyamuna15
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views20 pages

Flask Templates and Static Files Guide

This document provides a beginner-friendly guide to using Templates and Static Files in Flask, explaining the roles of HTML templates and static files like CSS and JavaScript. It covers the Jinja2 template engine, demonstrating how to use variables, loops, and conditions within templates, as well as the importance of a structured folder layout for organizing templates and static files. The document also includes practical examples and analogies to illustrate concepts clearly.

Uploaded by

billiyamuna15
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Perfect let’s go deep into Templates & Static Files in Flask in very simple English with extra

theory, examples, and analogies (beginner-friendly).

Templates & Static Files in Flask

When you make websites with Flask, you need two main things:

1. Templates (HTML files) → for the content (what users see on the screen).

2. Static files (CSS, JavaScript, Images, etc.) → for the design and behavior.

Let’s break it down step by step.

1. What are Templates?

• A template is basically an HTML file that Flask can fill with dynamic data before sending it to
the browser.

• Flask uses a special system called Jinja2 for templates.

• Jinja2 lets you write placeholders like {{ name }} inside HTML. Flask replaces them with real
values when the page loads.

Example analogy:
Think of a wedding invitation card template.

• The template has placeholders: Dear [Name] and [Date of Wedding].

• When printing, you fill the placeholders with actual details (Nazeer, 20th Sep, etc.).

Flask templates work the same way.

Example: Simple Template

Folder structure:

[Link]

templates/

[Link]

[Link]

from flask import Flask, render_template

app = Flask(__name__)

@[Link]("/")

def home():

return render_template("[Link]", name="Nazeer")


if __name__ == "__main__":

[Link](debug=True)

templates/[Link]

<!doctype html>

<html>

<head>

<title>My First Template</title>

</head>

<body>

<h1>Hello, {{ name }}!</h1>

<p>Welcome to Flask templates.</p>

</body>

</html>

Explanation:

• render_template("[Link]", name="Nazeer") → tells Flask to open [Link] and replace


{{ name }} with "Nazeer".

• Output on browser:

• Hello, Nazeer!

• Welcome to Flask templates.

2. Template Features (Jinja2)

Templates are powerful because they allow:

• Variables: {{ name }}, {{ age }}, {{ [Link] }}

• Conditions:

• {% if logged_in %}

• <p>Welcome back!</p>

• {% else %}

• <p>Please log in.</p>

• {% endif %}

• Loops:

• <ul>

• {% for item in items %}


• <li>{{ item }}</li>

• {% endfor %}

• </ul>

• Template Inheritance: You can make a base template (like a skeleton) and reuse it for
multiple pages.

This saves time and avoids repeating the same HTML again and again.

3. What are Static Files?

• Static files are things that do not change when the app runs.

• Examples:

o CSS files (design/style)

o JavaScript files (client-side logic)

o Images (logos, backgrounds, icons)

Flask automatically looks for them in a folder named static/.

Example: Adding a CSS file

Folder structure:

[Link]

templates/

[Link]

static/

[Link]

[Link]

from flask import Flask, render_template

app = Flask(__name__)

@[Link]("/")

def home():

return render_template("[Link]")

if __name__ == "__main__":

[Link](debug=True)
templates/[Link]

<!doctype html>

<html>

<head>

<title>Static Example</title>

<!-- Link to static CSS file -->

<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">

</head>

<body>

<h1>Hello, Flask with CSS!</h1>

</body>

</html>

static/[Link]

body {

background-color: lightblue;

font-family: Arial, sans-serif;

h1 {

color: darkblue;

Explanation:

• url_for('static', filename='[Link]') → Flask builds the correct path to static/[Link].

• Browser will load this CSS file and style the page.

4. Why separate templates and static files?

• Separation of concerns:

o Templates → page content and structure (HTML).

o Static → styling, images, and behavior.

• This makes apps organized and easier to maintain.

Analogy:
Think of a book:

• The content (text) = templates.


• The cover, fonts, pictures = static files.

5. Real-World Example

Imagine building a student portal:

• Templates:

o [Link], [Link], [Link].

• Static:

o [Link] → styles all pages.

o [Link] → handles button clicks.

o [Link] → shows on top of every page.

Got it Let’s go step by step and explain Jinja2 template engine in very simple English with theory
+ examples for beginners.

Jinja2 Template Engine in Flask

When you build websites using Flask, you don’t want to write separate HTML pages for every small
change.
For example:

• If you want to show different names on the same HTML page,

• Or repeat items like a list of products or students,

• Or show messages only if a condition is true,

You need a template engine.

Flask uses Jinja2 (it comes built-in with Flask) to make HTML pages more dynamic (flexible and
reusable).

1. Jinja2 Variables

You can pass Python values into an HTML file and display them.

Example:

[Link]

from flask import Flask, render_template

app = Flask(__name__)

@[Link]('/')
def home():

name = "Nazeer"

return render_template("[Link]", username=name)

if __name__ == '__main__':

[Link](debug=True)

[Link] (inside templates folder)

<!DOCTYPE html>

<html>

<head>

<title>Jinja2 Variables</title>

</head>

<body>

<h1>Hello, {{ username }}!</h1>

</body>

</html>

Explanation (line by line):

• name = "Nazeer" → Python variable.

• render_template("[Link]", username=name) → sends variable name to HTML as


username.

• In HTML → {{ username }} → shows the value (Nazeer).

{{ ... }} → Used for variables in Jinja2.

2. Jinja2 Loops

You can use loops in HTML to repeat content (like showing items from a list).

Example:

[Link]

@[Link]('/students')

def students():

names = ["Ali", "Rahul", "Meena", "Sara"]

return render_template("[Link]", student_list=names)

[Link]

<!DOCTYPE html>
<html>

<head>

<title>Student List</title>

</head>

<body>

<h2>Student Names:</h2>

<ul>

{% for student in student_list %}

<li>{{ student }}</li>

{% endfor %}

</ul>

</body>

</html>

Explanation:

• Python sends a list: ["Ali", "Rahul", "Meena", "Sara"].

• {% for student in student_list %} → loop in Jinja2.

• <li>{{ student }}</li> → shows each student inside <li>.

• {% endfor %} → ends the loop.

{% ... %} → Used for logic (loops, if conditions) in Jinja2.

3. Jinja2 Conditions

You can show content only when a condition is true.

Example:

[Link]

@[Link]('/marks')

def marks():

score = 85

return render_template("[Link]", marks=score)

[Link]

<!DOCTYPE html>

<html>

<head>
<title>Marks</title>

</head>

<body>

<h2>Your Marks: {{ marks }}</h2>

{% if marks >= 50 %}

<p> You passed the exam!</p>

{% else %}

<p> You failed. Try again.</p>

{% endif %}

</body>

</html>

Explanation:

• marks = 85 → sent from Python to HTML.

• {% if marks >= 50 %} → checks condition.

• If true → shows “You passed”.

• Else → shows “You failed”.

• {% endif %} → ends condition.

Summary

• {{ variable }} → To display Python variables in HTML.

• {% for ... %}{% endfor %} → To write loops in HTML.

• {% if ... %}{% else %}{% endif %} → To write conditions in HTML.

Jinja2 = Bridge between Python code and HTML page.


It makes your webpages dynamic, reusable, and powerful.

Perfect Let’s go step by step and explain the Flask folder structure — especially templates/ and
static/ — in very simple English for beginners, with extra theory, examples, and best practices.

Folder Structure in Flask

When you create a Flask project, you don’t just keep everything in one file.
Instead, Flask follows a simple but organized folder structure so your project is clean and easy to
manage.

The two most important folders in Flask are:


1. templates/ → for all your HTML files.

2. static/ → for all your CSS, JavaScript, images, and other static files.

1. templates/ folder

• Flask uses Jinja2 template engine (we already learned this).

• All HTML files go inside the templates folder.

• Flask automatically looks in the templates/ folder when you use render_template().

Example folder structure:

my_flask_app/

├── [Link]

├── templates/

│ ├── [Link]

│ ├── [Link]

│ └── [Link]

Example code:

[Link]

from flask import Flask, render_template

app = Flask(__name__)

@[Link]('/')

def home():

return render_template("[Link]")

@[Link]('/about')

def about():

return render_template("[Link]")

if __name__ == '__main__':

[Link](debug=True)

[Link] (inside templates folder)

<!DOCTYPE html>
<html>

<head>

<title>Home</title>

</head>

<body>

<h1>Welcome to Flask Home Page</h1>

</body>

</html>

Key Points

• Must keep HTML inside templates/ folder.

• You don’t need to write full path like "templates/[Link]".

• Flask already knows to search in templates/.

2. static/ folder

• This folder is used for static files → things that don’t change.

• Example:

o CSS files ([Link])

o JavaScript files ([Link])

o Images ([Link], [Link])

Example folder structure:

my_flask_app/

├── [Link]

├── templates/

│ └── [Link]

├── static/

├── [Link]

├── [Link]

└── [Link]

Example HTML using static files:

[Link]

<!DOCTYPE html>
<html>

<head>

<title>Static Files Example</title>

<!-- Linking CSS from static folder -->

<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">

</head>

<body>

<h1>Welcome to My Flask Page</h1>

<!-- Adding an image from static folder -->

<img src="{{ url_for('static', filename='[Link]') }}" alt="Logo">

</body>

</html>

Key Points

• All static files must go inside static/ folder.

• Use url_for('static', filename='file_name') to access them.

o Example: url_for('static', filename='[Link]') → /static/[Link]

3. Combined Folder Structure

my_flask_app/

├── [Link] → Main Flask application

├── templates/ → All HTML pages

│ ├── [Link]

│ └── [Link]

└── static/ → All CSS, JS, images

├── [Link]

├── [Link]

└── [Link]

4. Why This Structure is Important?


• Organization → HTML in one folder, CSS/JS/images in another.

• Reusability → You can use the same static files across multiple pages.

• Convention → Flask automatically knows where to look (no need to manually set paths).

• Scalability → If your project grows, you can still manage it easily.

5. Real-Life Analogy

Think of a house:

• templates/ = rooms → each room has different content (HTML pages).

• static/ = decorations → wall paint, lights, furniture (CSS, JS, images).

• [Link] = house entrance → connects everything together.

Perfect Let’s now go deeper into adding CSS, JavaScript, and Images in Flask. I’ll explain in very
simple English with theory + examples for beginners.

Adding CSS / JS / Images in Flask

In Flask, we use the static/ folder to store all the static files like:

• CSS → for styling your webpage (colors, layout, fonts).

• JavaScript (JS) → for adding interactivity (buttons, alerts, animations).

• 🖼 Images → for adding pictures, icons, or logos.

Flask automatically understands that all static files are inside the static/ folder.
So whenever you want to use them in HTML, you must call them using:

{{ url_for('static', filename='file_name') }}

1. Adding CSS in Flask

Folder Structure

my_flask_app/

├── [Link]

├── templates/

│ └── [Link]

└── static/

└── [Link]

[Link] (inside static/)


body {

background-color: lightblue;

font-family: Arial, sans-serif;

h1 {

color: darkblue;

text-align: center;

[Link] (inside templates/)

<!DOCTYPE html>

<html>

<head>

<title>Flask CSS Example</title>

<!-- Link CSS file from static folder -->

<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">

</head>

<body>

<h1>Hello Flask with CSS!</h1>

</body>

</html>

Explanation

• static/[Link] → stores your CSS file.

• <link rel="stylesheet"...> → connects HTML to CSS.

• {{ url_for('static', filename='[Link]') }} → Flask automatically finds and serves the CSS file.

2. Adding JavaScript (JS) in Flask

Folder Structure

my_flask_app/

├── [Link]

├── templates/
│ └── [Link]

└── static/

└── [Link]

[Link] (inside static/)

function showMessage() {

alert("Hello! This is a JavaScript alert from Flask.");

[Link]

<!DOCTYPE html>

<html>

<head>

<title>Flask JS Example</title>

<!-- Link CSS (optional) -->

</head>

<body>

<h1>Flask with JavaScript</h1>

<button onclick="showMessage()">Click Me</button>

<!-- Link JS file from static folder -->

<script src="{{ url_for('static', filename='[Link]') }}"></script>

</body>

</html>

Explanation

• static/[Link] → stores your JavaScript file.

• <script src="..."> → loads JS into your page.

• showMessage() → function runs when the button is clicked.

• onclick="showMessage()" → connects the button to JS function.

3. Adding Images in Flask

Folder Structure

my_flask_app/


├── [Link]

├── templates/

│ └── [Link]

└── static/

└── [Link]

[Link]

<!DOCTYPE html>

<html>

<head>

<title>Flask Image Example</title>

</head>

<body>

<h1>My Flask Website</h1>

<!-- Load image from static folder -->

<img src="{{ url_for('static', filename='[Link]') }}" alt="Website Logo" width="200">

</body>

</html>

Explanation

• static/[Link] → stores your image.

• <img src="..."> → loads image.

• {{ url_for('static', filename='[Link]') }} → Flask serves the image file.

• alt="..." → text shown if image doesn’t load.

• width="200" → resizes image.

4. Putting Everything Together

Folder structure:

my_flask_app/

├── [Link]

├── templates/

│ └── [Link]

└── static/
├── [Link]

├── [Link]

└── [Link]

[Link]

<!DOCTYPE html>

<html>

<head>

<title>Flask Website</title>

<!-- Link CSS -->

<link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">

</head>

<body>

<h1>Welcome to My Flask Website</h1>

<!-- Add Image -->

<img src="{{ url_for('static', filename='[Link]') }}" alt="Logo" width="150">

<br><br>

<!-- Add Button with JS -->

<button onclick="showMessage()">Click Me</button>

<!-- Link JS -->

<script src="{{ url_for('static', filename='[Link]') }}"></script>

</body>

</html>

5. Why Do We Use url_for() Instead of Direct Path?

• Bad practice:

• <link rel="stylesheet" href="/static/[Link]">

This may break if your app is deployed on a different URL or folder.

• Good practice:
• <link rel="stylesheet" href="{{ url_for('static', filename='[Link]') }}">

Flask automatically generates the correct path for your files.

Summary

• CSS → Used for styling, linked with <link rel="stylesheet"...>.

• JS → Used for interactivity, linked with <script src="...">.

• Images → Added using <img src="...">.

• All static files must go inside static/ folder.

• Always use url_for('static', filename='...') for safety.

Perfect Let’s go step by step and explain how to create a REST API in Flask with a route like
/api/students that returns a JSON list of students. I’ll use simple English and give theory + code +
explanation line by line.

What is a REST API?

• API = Application Programming Interface → it’s a way for two programs to talk to each other.

• REST API = a type of API that follows simple rules to send and receive data, usually using
HTTP (the same system websites use).

In simple words:

• A website returns HTML (pages you can see).

• An API returns data (like JSON) that can be used by another program, app, or frontend.

Why JSON in REST API?

• JSON = JavaScript Object Notation → a lightweight format for sharing data.

• Looks like Python dictionary, but universal.

• Example:

• {

• "name": "Nazeer",

• "age": 22

• }

• Easy to read for humans

• Easy to process for machines


Flask REST API Example: /api/students

Folder structure:

my_flask_api/

├── [Link]

Code in [Link]

from flask import Flask, jsonify

app = Flask(__name__)

# Create a route for API

@[Link]('/api/students')

def get_students():

# A Python list of students

students = [

{"id": 1, "name": "Ali", "age": 20},

{"id": 2, "name": "Meena", "age": 21},

{"id": 3, "name": "Rahul", "age": 22}

# Return the list in JSON format

return jsonify(students)

if __name__ == '__main__':

[Link](debug=True)

Explanation (Line by Line)

from flask import Flask, jsonify

• Flask → used to create the app.

• jsonify → converts Python data (like list/dict) into JSON (so API can send it).

app = Flask(__name__)

• Creates the Flask app.


• __name__ tells Flask where the app is located.

@[Link]('/api/students')

• This defines a route → when user visits /api/students, this function will run.

• Example: [Link]

def get_students():

• A function that will run whenever /api/students is requested.

students = [...]

• A Python list of dictionaries.

• Each dictionary represents one student with id, name, and age.

return jsonify(students)

• Converts Python list into JSON format.

• Sends it back as an API response.

• Example output in browser:

• [

• {"id": 1, "name": "Ali", "age": 20},

• {"id": 2, "name": "Meena", "age": 21},

• {"id": 3, "name": "Rahul", "age": 22}

• ]

if __name__ == '__main__':

• Runs the Flask app when the file is executed.

[Link](debug=True)

• Starts the server on [Link]

• debug=True → automatically restarts server if code changes + shows error messages.

How to Test It?

1. Run the file:


2. python [Link]

3. Open browser and go to:

4. [Link]

5. You will see JSON data like this:

6. [

7. {"id": 1, "name": "Ali", "age": 20},

8. {"id": 2, "name": "Meena", "age": 21},

9. {"id": 3, "name": "Rahul", "age": 22}

10. ]

Why REST API is Useful?

• Frontend + Backend connection: Frontend (HTML/React/Angular) can call Flask API to get
data.

• Mobile apps: Mobile apps can call API to fetch or send data.

• Integration: Other systems can use your API (like weather apps calling OpenWeather API).

In short:

• A route (/api/students) returns JSON.

• jsonify() converts Python data to JSON.

• REST API makes it easy to share data between apps.

You might also like