2017-05-31 83 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']

相關問題