代码之家  ›  专栏  ›  技术社区  ›  Martin Thoma

为什么pelican/jinja2没有再次设置变量?

  •  1
  • Martin Thoma  · 技术社区  · 6 年前

    我有以下脚本:

    <div class="blog-archives">
        {% set last_year = 0 %}
        {% for article in dates %}
            {% set year = article.date.strftime('%Y') %}
            {% if last_year != year %}
                <h2 id="{{year }}" title="last_year={{last_year}}"><a href="#{{year}}">{{ year }}</a></h2>
                {% set last_year = year %}
            {% endif %}
            {% set next_year = 0 %}
            {% if not loop.last %}
                {% set next = loop.index0 + 1 %}
                {% set next_article = dates[next] %}
                {% set next_year = next_article.date.strftime('%Y') %}
            {% endif %}
            {% if next_year != year %}
                <article class="last-entry-of-year">
            {% else %}
                <article>
            {% endif %}
            <a href="{{ SITEURL }}/{{ article.url }}">{{ article.title }} {%if article.subtitle %} <small> {{ article.subtitle }} </small> {% endif %} </a>
            <time pubdate="pubdate" datetime="{{ article.date.isoformat() }}">{{ article.locale_date }}</time>
            </article>
        {% endfor %}
    </div>
    

    enter image description here

    但实际上我

    enter image description here

    {% set last_year = year %} last_year 始终为0。有人知道为什么和怎么修吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   blhsing    6 年前

    与Python不同,在Jinja2中 for 循环有自己的名称空间;因此,在循环内设置的变量是循环的局部变量,一旦超出循环,同名变量将还原为外部作用域的变量。

    namespace 解决此问题的对象:

    {% set ns = namespace(last_year=0) %}
    {% for article in dates %}
        {% set year = article.date.strftime('%Y') %}
        {% if ns.last_year != year %}
            <h2 id="{{year }}" title="last_year={{ns.last_year}}"><a href="#{{year}}">{{ year }}</a></h2>
            {% set ns.last_year = year %}
    

    请参阅 namespace 详情。