Jinja2 (Pongo2) 指南
Pongo2 是 Jinja2 的 Go 语言实现,与 Python Jinja2 约 90% 兼容。然而,剩余 10% 的差异正是导致大部分渲染错误的原因。本指南帮助你规避所有已知陷阱。
在 config.json 中设置:
{ "templateEngine": "jinja2"}{# 自动转义 HTML #}{{ config.siteName }}
{# 输出原始 HTML(必须用于富文本内容) #}{{ post.content|safe }}
{# 带默认值 -- 注意冒号语法 #}{{ post.feature|default:"/images/fallback.jpg" }}{# base.html #}<!DOCTYPE html><html><head><title>{% block title %}{{ config.siteName }}{% endblock %}</title></head><body> {% include "partials/header.html" %} {% block content %}{% endblock %} {% include "partials/footer.html" %}</body></html>
{# index.html #}{% extends "base.html" %}{% block title %}首页 | {{ config.siteName }}{% endblock %}{% block content %} {% for post in posts %} <h2><a href="{{ post.link }}">{{ post.title }}</a></h2> {% endfor %}{% endblock %}{% for post in posts %} {# forloop.Counter 从 1 开始,forloop.Counter0 从 0 开始 #} <span>{{ forloop.Counter }}. {{ post.title }}</span>{% endfor %}Pongo2 与标准 Jinja2 的关键差异
Section titled “Pongo2 与标准 Jinja2 的关键差异”以下差异会直接导致渲染失败或输出错误:
1. 过滤器参数用冒号,不用括号
Section titled “1. 过滤器参数用冒号,不用括号”{# 正确 #}{{ value|default:"fallback" }}{{ name|truncatechars:20 }}
{# 错误 -- 会导致解析报错 #}{{ value|default("fallback") }}2. post.date 是字符串,不是时间对象
Section titled “2. post.date 是字符串,不是时间对象”{# 正确 -- 直接输出 #}<time>{{ post.date }}</time>
{# 错误 -- post.date 不是 time.Time,会报错 #}<time>{{ post.date|date:"2006-01-02" }}</time>3. include 路径相对于 templates/ 根目录
Section titled “3. include 路径相对于 templates/ 根目录”{# 正确 -- 始终从 templates/ 开始 #}{% include "partials/header.html" %}
{# 错误 -- 不是相对于当前文件 #}{% include "../partials/header.html" %}4. 所有标签必须写在同一行
Section titled “4. 所有标签必须写在同一行”{# 正确 #}{% if post.isTop %}<span>置顶</span>{% endif %}
{# 也正确 -- 标签本身在一行内 #}{% if post.isTop %} <span>置顶</span>{% endif %}文章列表(含空状态)
Section titled “文章列表(含空状态)”{% if posts %} {% for post in posts %} <article> {% if post.feature %} <img src="{{ post.feature }}" alt="{{ post.title }}" /> {% endif %} <h2><a href="{{ post.link }}">{{ post.title }}</a></h2> <time>{{ post.date }}</time> {% for tag in post.tags %} <a href="{{ tag.link }}">{{ tag.name }}</a> {% endfor %} </article> {% endfor %}{% else %} <p>暂无文章</p>{% endif %}<nav> {% if pagination.prev %} <a href="{{ pagination.prev }}">上一页</a> {% endif %} {% if pagination.next %} <a href="{{ pagination.next }}">下一页</a> {% endif %}</nav>访问主题配置
Section titled “访问主题配置”<style>:root { --primary: {{ theme_config.primaryColor }}; }</style>
{% if theme_config.showSidebar %} {% include "partials/sidebar.html" %}{% endif %}
{# 注入自定义代码时必须用 safe #}{{ theme_config.headerScript|safe }}完整变量列表请查阅模板变量参考。