2017-05-31 133 views
0

我已经在Python配置文件定义了以下解释:如何访问Jina2模板中的特定字典元素?

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

我有以下的Jinja2模板:

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

{% 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 %} 

而且我通过调用这个

当我生成我的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元素在我的模板?

+1

'article.author'确实是string/unicode类型的吗? – Feodoran

回答

1

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']

相关问题