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

2024-04-25 23:21:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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>

生成鹈鹕模板时,出现以下错误:

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元素?你知道吗


Tags: namediv模板httpurlherearticleauthors
1条回答
网友
1楼 · 发布于 2024-04-25 23:21:02

article.author不仅仅是'Your Name',它是an ^{} 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']。你知道吗

相关问题 更多 >