【问题标题】:With Pelican, how to set or access variables between Python code and themes?使用 Pelican,如何在 Python 代码和主题之间设置或访问变量?
【发布时间】:2026-02-21 18:55:02
【问题描述】:

我需要将原始源文件名(*.md 文件)传递到 sidebar.html。我怎样才能做到这一点?

从这个网站(http://pelican.readthedocs.org/en/3.6.3/themes.html)了解到有一些变量是可用的,pelicanconf.py文件中的所有大写字母变量也是可用的,但是不知道如何获取原始源文件等信息在主题文件中。

【问题讨论】:

  • 您能提供更多信息吗?你需要它做什么,是用作 URL slug 的文件名,重要的路径等等。

标签: python pelican


【解决方案1】:

我认为可能有更简单的方法,但使用 jinja 过滤器对我来说效果很好 (http://linkpeek.com/blog/how-to-add-a-custom-jinja-filter-to-pelican.html)

采取的步骤:

预设置

我将原始标记文件的名称设为 YEAR-MONTH-DAY-NAME 格式,以便从页面的 url 中恢复。

创建过滤器

过滤器给定了url,从url中我可以恢复原来的源md文件路径。

def tosource(url):
    # example input
    # posts/2014/01/26/python-unittest-structure/index.html
    # posts/2014/01/26/ocaml-vs-java/index.html
    # posts/2014/01/25/why-ocaml-comparison-with-python/index.html

    if url.startswith("posts"):
        (posts, year, month, day, name) = url.split('/')[:-1]
        res = "%s/%s/%s-%s-%s-%s.md" % (year, month, year, month, day, name)
    else:
        res = "/" # implement later
    return res

更新 pelicanconf.py

教鹈鹕过滤器的名称和位置。

import sys
sys.path.append('.')

import sourcename
JINJA_FILTERS = {'sourcename':sourcename.tosource}

OPENCONTENT = "open:///pelican/knowledge_blog/content"

正如http://docs.getpelican.com/en/3.5.0/themes.html#theming-pelican 中所写,conf 文件中的所有大写字母变量都可以在主题文件中访问。

更新 sidebar.html

我在sidebar.html中添加了一行代码,使用Jinja过滤器获取原始md文件路径。

Click to <a href="{{ OPENCONTENT }}/{{ output_file|sourcename }}">Edit</a>

生成html

运行make html 并进行测试。

【讨论】: