简体   繁体   中英

Do statement not working in jinja

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?

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'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM