那我們來進一步介紹 Jinja2 的進階用法,包括:


一、模板繼承(Template Inheritance)

讓你可以定義一個基本結構,其他頁面只要「擴充」它,不必重複寫整份 HTML。

templates/base.html

<!DOCTYPE html>
<html>
<head><title>{% block title %}我的網站{% endblock %}</title></head>
<body>
    <header><h1>我的網站</h1></header>
    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

templates/index.html

{% extends 'base.html' %}

{% block title %}首頁{% endblock %}

{% block content %}
<p>這是首頁內容。</p>
{% endblock %}

二、宏(Macros)- 重複 UI 的最佳解法

類似函數,可重複渲染 HTML。

templates/macros.html

{% macro input(name, type='text', placeholder='') %}
  <input type="{{ type }}" name="{{ name }}" placeholder="{{ placeholder }}">
{% endmacro %}

使用 macro

{% import 'macros.html' as forms %}
{{ forms.input('username', placeholder='請輸入使用者名稱') }}

三、自訂過濾器(Custom Filters)

在 Python 中註冊一個函數當作過濾器。

app.py

def reverse_string(s):
    return s[::-1]

app.jinja_env.filters['reverse'] = reverse_string

使用:

{{ "hello"|reverse }}  {# 顯示為 "olleh" #}

四、安全性注意:{{ value|safe }}

如果你要顯示 HTML 原始碼(如 <strong>你好</strong>),要用 safe 過濾器,否則會被轉義為字串。


需要我幫你做一個完整的範例專案壓縮包,還是想繼續學習表單渲染、CSRF、或是 template 中的動態載入?

文章標籤
全站熱搜
創作者介紹
創作者 liusming 的頭像
liusming

劉老師的跨域創想工坊

liusming 發表在 痞客邦 留言(0) 人氣(4)