2017-10-12 9 views
1

내에서 할당의 비 지속성에 대한 보상 :은 "범위 지정 동작"하위 섹션 아래에있는 신사 문서의 <a href="http://jinja.pocoo.org/docs/2.9/templates/#assignments" rel="nofollow noreferrer">Assignments section</a> 당 Jinja2 루프

Please keep in mind that it is not possible to set variables inside a block and have them show up outside of it. This also applies to loops. The only exception to that rule are if statements which do not introduce a scope.

나는 for 루프에서 else 문의 기능을 이해 그리고 loop.index과 같은 특수 변수가 있지만 내 문제가 해결되지 않습니다.

기사를 출력하는 위젯이 특정 조건과 일치하는 경우에만 표시됩니다. 테스트 케이스를 줄이기 위해, 여기에 빠른 예제 코드입니다 :이 작동하지 않습니다 물론

{% set maxiterations = 3 %} 
{% set iterations = 0 %} 
{% for item in seq %} 
    {% if item == "bar" and iterations < maxiterations %} 
    {{ item.foo }} 
    {% set iterations = iterations + 1 %} 
    {% endif %} 
{% endfor %} 

: 반복을 1 항상 동일한 것이다. loop.index 도움이되지 않습니다. 저는 건너 뛴 반복 횟수를 계산하고 싶지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?

답변

1

@SumanKalyan이 (가 루프 외부에서 설정 한 때 루프 내부의 반복을 수정할 수 없습니다) 절대적으로 올바른 동안 , 나는 그의 해결책을 찾지 못했고 Jinja2에서 사용 가능한 do 진술도 내 맥락에서 이해되는 것처럼 보인다. SumanKalyan의 제안 또는 같은 do 항상 반환 오류 @ 시도

는 :

CRITICAL: TemplateSyntaxError: Encountered unknown tag 'iterations'. 
Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. 
The innermost block that needs to be closed is 'if'. 

do에 대한 지원의 부족 때문에 내 특정 응용 프로그램 (Pelican)이 확장의 부족으로 밝혀졌다. 간단히 지정할 수는 있지만 대신 다른 경로를 선택했습니다. 나는 다른 대답을 발견했다. 실현을 통해 크게 도움을 받았다. Jinja2 for 루프는 조건문을 지원한다. 따라서 :

{% set max_iterations = 3 %} 
{% for item in seq if item == "bar" %} 
    {% if index.loop < max_iterations %} 
     {{ item.foo }} 
    {% endif %} 
{% endfor %} 

이 케이스의 핵심 부분 만족시키는 유일한 출력 item.fooitem == bar 경우; 그것을 반복 된 부분 집합 seq의 일부로 만들지 마십시오.

실제로 구현 한 경우 (여기에 제시된 테스트 케이스 외)에는 여러 조건이 있습니다. 하나는 외부에서 설정된 변수의 진실성과 특정 루프 반복을 기반으로 항목을 건너 뛸 필요가있었습니다 (처음 발생했습니다). 방법이의 예는 해결된다 : 호기심에 대한

{% set baz == true %} 
{% if baz %} 
    {% set max_iterations = 4 %} 
{% else %} 
    {% set max_iterations = 3 %} 
{% endif %} 

{% for item in seq if item == "bar" %} 
    {% if index.loop < max_iterations and not(baz and loop.index == 1) %} 
     {{ item.foo }} 
    {% endif %} 
{% endfor %} 

, (또한 viewable in context) 실제 코드 :

{# Only show the widget content if: 
    - There a configured count of articles to display 
    - There's any articles in articles_list 
    - There's at least 2 articles... 
    - ...Or at least 1 article if the widget count is set to 1 #} 

{% if ARTICLES_WIDGET_COUNT and articles_list|length != 0 and (articles_list|length > 1 or ARTICLES_WIDGET_COUNT == 1) %} 
    <aside class="siteFooter_articles widget"> 
     {% if ARTICLES_WIDGET_NAME %} 
      <h1 class="widget_title">{{ ARTICLES_WIDGET_NAME }}</h1> 
     {% endif %} 

     <ol class="imageList list-noType"> 
      {# If this is the index page, the first article is always displayed. 
      It gets skipped inside the loop, so increment the counter #} 
      {% if isindex %} 
       {% set max_iterations = ARTICLES_WIDGET_COUNT + 1 %} 
      {% else %} 
       {% set max_iterations = ARTICLES_WIDGET_COUNT %} 
      {% endif %} 

      {# Skip displaying this article if this is the page for the article being displayed in full 
      If this isn't an article page, always display the item (note the additional condition below for index pages) #} 
      {% for article in articles_list if article.url != thisarticle.url or thisarticle == null %} 
       {# If this is the index page and the first loop iteration, the article to be displayed in the widget would be the same one 
       displayed in full on the page. So, skip it. (Note the counter is incremented before the loop to account for this.) #} 

       {% if not(loop.index == 1 and isindex) %} 
        {% set articles_widget = true %} 
        {% include 'includes/articleitem.html' %} 
       {% endif %} 

       {# If the set number of articles have been added to the widget, we're done here. #} 
       {% if loop.index == max_iterations %} {% break %} {% endif %} 
      {% endfor %} 
     </ol> 

     <p class="readMore"> 
      <a class="readMore_link" href="{{ SITEURL }}/{{ ARTICLES_URL }}">More...</a> 
     </p> 
    </aside> 
{% endif %} 
1

루프 외부에서 '반복'을 설정하면 루프 내에서 수정할 수 없습니다. 당신은 객체가 아닌 '반복'에 대한 스칼라를 사용하여이 동작을 물리 칠 수 있습니다

{% set maxiterations = 3 %} 
{% set iterations = [0] %} 
{% for item in seq %} 
    {% if item == "bar" and iterations[0] < maxiterations %} 
    {{ item.foo }} 
    {% iterations.append(iterations.pop() + 1) %} 
    {% endif %} 
{% endfor %} 
+0

는이 솔루션을 시도 할 때, 내가 얻을 : 'CRITICAL : TemplateSyntaxError을 : 알 수없는 발생했습니다 태그 'iterations'. Jinja는 'elif'또는 'else'또는 'endif'태그를 찾고있었습니다. 닫아야 할 가장 깊은 블록은 'if'입니다. – Tohuw

+0

문 앞에서'do'를 시도했지만 동일한 오류가 발생했지만 이번에는 알 수없는 태그가'do'입니다. 이것이 [Pelican] (http://getpelican.com)의 한계 일 가능성이 있습니까? – Tohuw

+0

그것이 작동하지 않는 이유를 알아 냈습니다. 적어도'do'로 ... 내 아래 답변을보십시오. – Tohuw