访问flask模板字典变量

时间:2017-01-02 16:16:15

标签: python flask

我有flask变量{{blogposts}}输出:

[{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data here', u'post_title': u'data here'}, 
{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data here', u'post_title': u"data here"}, 
{u'MONTH': 12, u'YEAR': 2016, u'post_name': u'data here', u'post_title': u'data here'}] 

我有一个烧瓶模板,输出如下:

<ul>
    {% for blogpost in blogposts %}
        <li>
            <a href="http://blog.site.com/wordpress/{{blogpost.MONTH}}/{{blogpost.YEAR}}/{{blogpost.post_name}}">
                {{blogpost.post_title}}
            </a>
        </li>
    {% else %}
        <li>no blog posts right now...</li>
    {% endfor %}
        <div class="clearL"> </div>
    </ul>

RENDERED HTML

<li>
                    <a href="http://blog.site.com/wordpress///">

                    </a>
                </li>

                <li>
                    <a href="http://blog.site.com/wordpress///">

                    </a>
                </li>

                <li>
                    <a href="http://blog.site.com/wordpress///">

                    </a>
                </li>

                <li>
                    <a href="http://blog.site.com/wordpress///">

                    </a>
                </li>

我想访问<{strong> valuemonth,post_name'和year(按此顺序)的post_title,而不是输出:

 MONTH YEAR post_name post_title MONTH YEAR post_name post_title MONTH YEAR post_name post_title 

我该如何做到这一点?

谢谢

2 个答案:

答案 0 :(得分:1)

尝试:

{% for blogpost in blogposts %}
    <p> Month: {{ blogpost.MONTH }} </p> 
    <p> Year: {{ blogpost.YEAR }} </p> 
    <p> Name: {{ blogpost.post_name }}</p> 
    <p> Title: {{ blogpost.post_title }}</p>
{% endfor %}

答案 1 :(得分:0)

    Can try this !! 
    {% for row_index in blogposts %}
     {% for key,value in row_index.iteritems() %}
              {{key|safe}}
          {{ value|safe }}
      <br><br>
    {% endfor %}
     {% endfor %}

Even this can work 
    {% for row_index in blogposts %}
     {% for key in row_index.iteritems() %}
              {{key|safe}}
          {{ row_index[key]|safe }}
      <br><br>
    {% endfor %}
     {% endfor %}