如何访问 Jina2 模板中的特定字典元素?

How do I access a specific dictionary element in a Jina2 template?

我在 python 配置文件中定义了以下字典:

AUTHORS = {
    u'MyName Here': {
        u'blurb': """ blurb about author""",
        u'friendly_name': "Friendly Name",
        u'url': 'http://example.com'
    }
}

我有以下 Jinja2 模板:

{% macro article_author(article) %}
    {{ article.author }}
    {{ AUTHORS }}
    {% if article.author %}
        <a itemprop="url" href="{{ AUTHORS[article.author]['url'] }}" rel="author"><span itemprop="name">{{ AUTHORS[article.author]['friendly_name'] }}</span></a> -
        {{ AUTHORS[article.author]['blurb'] }}
    {% endif %}
{% endmacro %}

我通过以下方式调用它:

<div itemprop="author creator" itemscope itemtype="http://schema.org/Person">
    {% from '_includes/article_author.html' import article_author with context %}
    {{ article_author(article) }}
</div>

当我生成 Pelican 模板时,出现以下错误:

CRITICAL: UndefinedError: dict object has no element <Author u'MyName Here'>

如果我从我的模板中删除 {% if article.author %} 块,页面会正确生成并正确显示 {{ AUTHORS }} 变量。它显然有一个 MyName Here 键:

<div itemprop="author creator" itemscope itemtype="http://schema.org/Person">
    MyName Here
    {u'MyName Here': {u'url': u'http://example.com', u'friendly_name': u'Friendly Name', u'blurb': u' blurb about author'}}
</div>

如何在我的模板中正确访问 MyName Here 元素?

article.author 不仅仅是 'Your Name',它是具有各种属性的 an Author instance。在你的情况下,你想要:

{% if article.author %}
    <a itemprop="url" href="{{ AUTHORS[article.author.name].url }}" rel="author">
        <span itemprop="name">{{ AUTHORS[article.author.name].friendly_name }}</span>
    </a> -
    {{ AUTHORS[article.author.name].blurb }}
{% endif %}

或者,要减少一些样板文件,您可以使用:

{% if article.author %}
    {% with author = AUTHORS[article.author.name] %}
        <a itemprop="url" href="{{ author.url }}" rel="author">
            <span itemprop="name">{{ author.friendly_name }}</span>
        </a> -
        {{ author.blurb }}
    {% endwith %}
{% endif %}

只要您 JINJA_ENVIRONMENTextensions 列表中有 'jinja2.ext.with_'

请注意,您可以在 Jinja 模板中使用 dot.notation 而不是 index['notation']