【问题标题】:Variable modified in loop does not persist outside the loop在循环中修改的变量不会在循环外持续存在
【发布时间】:2023-03-08 06:45:01
【问题描述】:
{% set title_org = nav_item.title.split(" ") %}
{% set title_mod = "" %}
{% for i in title_org %}
  {% if loop.index > 3 %}
    {% set title_mod = title_mod + ' ' + i %}
  {% endif %}
{% endfor %}
<a href="{{ nav_item.url }}" id="{{ id }}">{{ title_mod }}</a>

{{ title_mod }} 是一个空字符串,尽管在循环中连接。如何在 for 循环外检索更新后的 {{ title_mod }}

【问题讨论】:

    标签: python web jinja2 mkdocs


    【解决方案1】:

    你应该使用数组/字典之类的

    <p style="display:none;">
    {% set title_data = {'org': nav_item.title.split(" "), 'mod' : ""} %}
    {% for i in title_data.org %}
      {% if loop.index > 3 %}
        {{ title_data.update({'mod' : title_data.mod + ' ' + i}) }}
      {% endif %}
    {% endfor %}
    </p>
    <a href="{{ nav_item.url }}" id="{{ id }}">{{ title_data.mod }}</a>
    

    看起来像dupe

    【讨论】:

    • 我不知道为什么这首先需要放在字典中。尽管如此,我在您的第一行将'mod' = 更改为'mod' : 。然后它返回这个错误,jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got '.'
    • {% set title_data.update({'mod' : title_data.mod + ' ' + i}) %} 中的错误。我不确定是哪一个,我找不到update() 的任何文档 :(.
    • 我不知道为什么这首先需要放在字典中这就是 Jinja 处理全局/本地上下文变量的方式 - 只是一种解决方法。请立即尝试,因为我已经包含了不需要的 set
    • 如果没有set,它会返回另一个错误jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'title_data'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.。文档实际上在哪里?我在 Jinja2 网站上找不到这个。
    • 看起来我是移动的,无法尽快测试它很容易出错。现在缺少do 关键字,希望它现在可以工作:P
    猜你喜欢
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-27
    • 2020-04-21
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    相关资源
    最近更新 更多