Do statement not working in jinja

这一生的挚爱 提交于 2019-12-19 09:26:55

问题


I'm altering an existing web interface to view ROBOT doc libraries, which uses a mixture of jinja (Python inside HTML) and HTML. I have never worked with jinja or HTML before and am having issues getting even a simple test case to work. When the browser loads the docs, I want our project's directory structure for the docs to be preserved to make finding things easier, and so I want to use jinja to create the dir structure. Here is a snippet of the code I'm working with:

{% extends "base.html" %}
{% block body %}
<div class="well" id="left">
  <ul class="list-group list-unstyled">
    {% set collection_list = [] %}
    {% for collection in data.hierarchy %}
      {% if collection.collection_id|string == data.collection_id|string %}
          {% do collection_list.append(collection.path) %}
      {% else %}
        {% for link in collection.path_chain %}
          <li>
          <label class="tree-toggler nav-header"
                 title="file path: {{collection.path}}">{{link}}</label>
          <ul class="list-group  tree collapse"
              id={{link}}>
              </ul>
        {% endfor %}
          </li>
      {% endif %}

...there's more after that, but this is where I hit the error. It sets the collection_list var fine, and the if statements work, but when it goes to execute the 'do' statement it fails with:

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

I don't believe this is an unclosed loop or something because if I replace the do statement with a simple test print statement, it works. Does anyone know what I'm doing wrong?


回答1:


From the template documentation:

Expression Statement

If the expression-statement extension is loaded, a tag called do is available that works exactly like the regular variable expression ({{ ... }}); except it doesn’t print anything. This can be used to modify lists:

{% do navigation.append('a string') %}

You need to enable the Expression statement extension for this to work.

You didn't show how you load the Jinja2 environment, but loading extensions takes place via the extensions argument to the Environment() class:

jinja_env = Environment(extensions=['jinja2.ext.do'])


来源:https://stackoverflow.com/questions/39858191/do-statement-not-working-in-jinja

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!