IT TIP

Jinja2 : 루프 내부의 변수 값 변경

itqueen 2020. 12. 8. 20:32
반응형

Jinja2 : 루프 내부의 변수 값 변경


루프 내에서 루프 외부에서 선언 된 변수의 값을 변경하고 싶습니다. 그러나 항상 변경하면 초기 값이 루프 외부에 유지됩니다.

{% set foo = False %}

{% for item in items %}
  {% set foo = True %}
  {% if foo %} Ok(1)! {% endif %}
{% endfor %}

{% if foo %} Ok(2)! {% endif %}

이것은 다음을 렌더링합니다.

Ok(1)!

그래서 지금까지 찾은 유일한 (나쁜) 해결책은 다음과 같습니다.

{% set foo = [] %}

{% for item in items %}
  {% if foo.append(True) %} {% endif %}
  {% if foo %} Ok(1)! {% endif %}
{% endfor %}

{% if foo %} Ok(2)! {% endif %}

이것은 다음을 렌더링합니다.

Ok(1)!
Ok(2)!

그러나 그것은 매우 추합니다! 더 우아한 해결책이 있습니까?


사전 기반 접근법도 시도하십시오. 덜 추한 것 같습니다.

{% set vars = {'foo': False} %}

{% for item in items %}
  {% if vars.update({'foo': True}) %} {% endif %}
  {% if vars.foo %} Ok(1)! {% endif %}
{% endfor %}

{% if vars.foo %} Ok(2)! {% endif %}

이것은 또한 다음을 렌더링합니다.

Ok(1)!
Ok(2)!

문서에 언급 된대로 :

루프의 할당은 반복이 끝날 때 지워지며 루프 범위를 초과 할 수 없습니다.

그러나 버전 2.10부터 네임 스페이스를 사용할 수 있습니다.

    {% set ns = namespace(foo=false) %}      
    {% for item in items %}
      {% set ns.foo = True %}
      {% if ns.foo %} Ok(1)! {% endif %}
    {% endfor %}

    {% if ns.foo %} Ok(2)! {% endif %}

이렇게하면 템플릿 코드를 정리할 수 있습니다.

{% for item in items %}
  {{ set_foo_is_true(local_vars) }}
  {% if local_vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if local_vars.foo %} Ok(2)! {% endif %}

그리고 서버 코드 사용

items = ['item1', 'item2', 'item3']
#---------------------------------------------
local_vars = { 'foo': False }
def set_foo_is_true(local_vars):
  local_vars['foo'] = True
  return ''
env.globals['set_foo_is_true'] = set_foo_is_true    
#---------------------------------------------
return env.get_template('template.html').render(items=items, local_vars=local_vars)

이것은 다음과 같이 일반화 될 수 있습니다.

{{ set_local_var(local_vars, "foo", False) }}
{% for item in items %}
  {{ set_local_var(local_vars, "foo", True) }}
  {% if local_vars.foo %} Ok(1)! {% endif %}
{% endfor %}
{% if local_vars.foo %} Ok(2)! {% endif %}

그리고 서버 코드 사용

items = ['item1', 'item2', 'item3']
#---------------------------------------------
local_vars = { 'foo': False }
def set_local_var(local_vars, name, value):
  local_vars[name] = value
  return ''
env.globals['set_local_var'] = set_local_var
#---------------------------------------------
return env.get_template('template.html').render(items=items, local_vars=local_vars)

참고 URL : https://stackoverflow.com/questions/9486393/jinja2-change-the-value-of-a-variable-inside-a-loop

반응형