Template Fundamentals

Loading concept...

๐ŸŽญ Flask Templates: Building Web Pages Like Magic

Imagine youโ€™re a puppet master. You have a stage (your website), puppets (data), and scripts (templates). Instead of building a new stage for every show, you create one amazing stage and just change the puppets and their lines. Thatโ€™s exactly what Flask templates do!


๐ŸŒŸ What is Jinja2 Template Engine?

Think of Jinja2 as your magical assistant. You write a letter with blank spaces, and Jinja2 fills in those blanks with the right words every time!

The Magic Behind It

# Your Flask app gives data
name = "Emma"

# Your template has a blank
# Hello, {{ name }}!

# Jinja2 fills it in
# Hello, Emma!

Why is this awesome?

  • Write your HTML once, use it forever
  • Change content without touching the design
  • Keep your code clean and organized
graph TD A[๐Ÿ Flask App] -->|Sends Data| B[๐ŸŽญ Jinja2 Engine] B -->|Fills Blanks| C[๐Ÿ“„ Template] C -->|Creates| D[โœจ Final HTML Page]

๐Ÿ“ Template Expressions: Filling in the Blanks

Template expressions are like fill-in-the-blank games. You mark where you want something to appear, and Jinja2 puts it there!

The Double Curly Braces {{ }}

<!-- Template -->
<h1>Welcome, {{ username }}!</h1>
<p>You have {{ messages }} new messages.</p>

<!-- If username="Alex" and messages=5 -->
<!-- Result -->
<h1>Welcome, Alex!</h1>
<p>You have 5 new messages.</p>

You Can Do Math Too!

<p>Total: ${{ price * quantity }}</p>
<p>Half off: ${{ price / 2 }}</p>

Access Object Properties

<!-- If user = {"name": "Sara", "age": 12} -->
<p>Name: {{ user.name }}</p>
<p>Age: {{ user.age }}</p>

<!-- Or use brackets -->
<p>Name: {{ user['name'] }}</p>

๐ŸŽฎ Template Control Structures: Making Decisions

Just like in a video game where you choose different paths, templates can show different things based on conditions!

If Statements: Choose Your Path

{% if user.is_logged_in %}
    <p>Hello, {{ user.name }}!</p>
{% else %}
    <p>Please log in to continue.</p>
{% endif %}

Notice: We use {% %} for logic, not {{ }}!

For Loops: Repeat the Magic

<ul>
{% for fruit in fruits %}
    <li>๐ŸŽ {{ fruit }}</li>
{% endfor %}
</ul>

<!-- If fruits = ["Apple", "Banana", "Cherry"] -->
<!-- Result -->
<ul>
    <li>๐ŸŽ Apple</li>
    <li>๐ŸŽ Banana</li>
    <li>๐ŸŽ Cherry</li>
</ul>

Combining If + For

{% for item in cart %}
    {% if item.in_stock %}
        <p>โœ… {{ item.name }} - ${{ item.price }}</p>
    {% else %}
        <p>โŒ {{ item.name }} - Out of stock</p>
    {% endif %}
{% endfor %}
graph TD A[Start Loop] --> B{Check Condition} B -->|True| C[Show Content A] B -->|False| D[Show Content B] C --> E{More Items?} D --> E E -->|Yes| A E -->|No| F[Done!]

๐Ÿ—๏ธ Template Inheritance: The Family Tree

Imagine a family recipe book. Grandma has the basic recipe, and everyone adds their own twist. Template inheritance works the same way!

Why Inheritance?

Instead of copying the same header and footer on 100 pages, you write it once and share it everywhere!


๐Ÿ“‹ Base Templates and Blocks: The Master Blueprint

A base template is like a house blueprint. It shows where the rooms go, and each room can be decorated differently.

Creating a Base Template

<!-- base.html - The Blueprint -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <header>
        <h1>๐ŸŒŸ My Awesome Site</h1>
        <nav>Home | About | Contact</nav>
    </header>

    <main>
        {% block content %}
        <!-- Child pages fill this! -->
        {% endblock %}
    </main>

    <footer>
        <p>ยฉ 2024 My Site</p>
    </footer>
</body>
</html>

Blocks are like empty picture frames waiting for photos!


๐Ÿงฉ Extending Templates: Building on the Blueprint

Now letโ€™s decorate the rooms by extending the base template!

The extends Keyword

<!-- home.html -->
{% extends "base.html" %}

{% block title %}Home - My Site{% endblock %}

{% block content %}
<h2>Welcome Home! ๐Ÿ </h2>
<p>This is the home page content.</p>
{% endblock %}

What Happens?

graph TD A[base.html] -->|Provides Structure| B[home.html] B -->|Fills Blocks| C[Final Page] A -->|Header + Footer| C B -->|Main Content| C

Multiple Pages, One Base

<!-- about.html -->
{% extends "base.html" %}

{% block title %}About Us{% endblock %}

{% block content %}
<h2>About Our Team ๐Ÿ‘ฅ</h2>
<p>We love making websites!</p>
{% endblock %}
<!-- contact.html -->
{% extends "base.html" %}

{% block title %}Contact{% endblock %}

{% block content %}
<h2>Get in Touch ๐Ÿ“ง</h2>
<form>...</form>
{% endblock %}

Same header, footer, and style. Different content!


๐Ÿ“ฆ Including Templates: Reusable Puzzle Pieces

Sometimes you want to reuse a small piece across different pages. Like a LEGO brick you can snap in anywhere!

The include Statement

<!-- _navbar.html (the puzzle piece) -->
<nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
    <a href="/contact">Contact</a>
</nav>
<!-- Any page can include it -->
{% include "_navbar.html" %}

<h1>Welcome!</h1>
<p>Page content here...</p>

{% include "_footer.html" %}

When to Use Include vs Extend?

Use extends Use include
Page layout (whole structure) Small reusable parts
Header + Content + Footer Just the navbar
One base, many pages Same piece, many places
graph TD A[extends] -->|Full Page Structure| B[base.html โ†’ child.html] C[include] -->|Small Piece| D[_navbar.html anywhere]

๐Ÿ›ก๏ธ HTML Escaping: Staying Safe from Bad Guys

Imagine someone writes this in a comment form:

<script>alert('Hacked!')</script>

Without protection, this code would run on your website! ๐Ÿ˜ฑ

Jinja2 Escapes by Default

<!-- User input -->
comment = "<script>bad code</script>"

<!-- Template -->
<p>{{ comment }}</p>

<!-- Result (SAFE!) -->
<p>&lt;script&gt;bad code&lt;/script&gt;</p>

The scary symbols become harmless text!

What Gets Escaped?

Character Becomes Why
< &lt; Prevents HTML tags
> &gt; Prevents HTML tags
& &amp; Prevents special codes
" &quot; Prevents quote tricks

When You Trust the Content

<!-- Only use with YOUR safe HTML! -->
{{ trusted_html | safe }}

<!-- Or -->
{% autoescape false %}
{{ trusted_html }}
{% endautoescape %}

โš ๏ธ Warning: Only use safe with content YOU created!

graph TD A[User Input] --> B{Escaped?} B -->|Yes โœ…| C[Safe: Shows as text] B -->|No โŒ| D[Dangerous: Runs as code!]

๐ŸŽฏ Quick Summary

Concept Symbol Purpose
Expression {{ }} Display data
Control {% %} Logic (if, for)
Block {% block %} Placeholder for content
Extends {% extends %} Use a base template
Include {% include %} Insert a piece
Escape Automatic Keep site safe

๐Ÿš€ You Did It!

You now understand how Flask templates work! Like a puppet master, you can:

  • โœ… Create reusable page layouts
  • โœ… Fill in dynamic content
  • โœ… Make decisions in templates
  • โœ… Keep your site safe from attacks

Next step: Try building your own templates and watch the magic happen! ๐ŸŽญโœจ

Loading story...

No Story Available

This concept doesn't have a story yet.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

Interactive Preview

Interactive - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Interactive Content

This concept doesn't have interactive content yet.

Cheatsheet Preview

Cheatsheet - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Cheatsheet Available

This concept doesn't have a cheatsheet yet.

Quiz Preview

Quiz - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.

No Quiz Available

This concept doesn't have a quiz yet.