声明在Jinja中不起作用 [英] Do statement not working in jinja

查看:99
本文介绍了声明在Jinja中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在更改现有的Web界面以查看ROBOT文档库,该库使用了Jinja(HTML内的Python)和HTML的混合体.我以前从未使用过jinja或HTML,并且遇到了甚至无法使用简单测试用例的问题.当浏览器加载文档时,我希望保留文档的项目目录结构,以便于查找,因此,我想使用jinja创建dir结构.这是我正在使用的代码的一个片段:

{% 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 %}

...之后还有更多,但这是我遇到错误的地方.它将collection_list var设置为罚款,并且if语句可以正常工作,但是当执行'do'语句时,它将失败,并显示以下信息:

TemplateSyntaxError:遇到未知标签"do". Jinja正在寻找以下标签:'elif'或'else'或'endif'.需要关闭的最里面的块是'if'.

我不认为这是一个未封闭的循环,因为如果我将do语句替换为简单的测试print语句,它就可以工作.有人知道我在做什么错吗?

解决方案

来自模板文档:

表达声明

如果加载了表达式声明扩展名,则可以使用一个名为do的标记,该标记的工作方式与正则表达式({{ ... }})完全相同.除了不打印任何东西.这可以用来修改列表:

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

您需要启用表达式声明扩展,以便工作.

您没有显示如何加载Jinja2环境,但是加载扩展是通过

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

这篇关于声明在Jinja中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆