【问题标题】:check variable type inside Jinja2 in Flask在 Flask 中检查 Jinja2 中的变量类型
【发布时间】:2013-05-21 17:11:29
【问题描述】:

我创建的模板文件包含以下内容:

{% if type({'a':1,'b':2}) is dict %}
    print "Oh Yes!!"
{% else %}
    print "Oh No!!!"
{% endif %}

然后 Jinja2 回应说:

TemplateAssertionError: no test named 'dict'

我对 Jinja2 和 Flask 完全陌生

【问题讨论】:

    标签: variables types flask jinja2


    【解决方案1】:

    您正在寻找mapping test:

    {% if {'a': 1, 'b': 2} is mapping %}
        "Oh Yes!"
    {% else %}
        "Oh No!"
    {% endif %}
    

    但 Jinja 不是 Python,因此您无法访问所有内置函数(例如,typeprint 不存在,除非您将它们添加到 the context。在 Flask 中,您可以这样做context_processor decorator)。

    您实际上根本不需要print。默认情况下,所有内容都会输出(除非您在以extends 为父模板的子模板中,在这种情况下您可以执行interesting things like the NULL Master fallback,因为仅输出具有主模板中可用名称的块)。

    【解决方案2】:

    如果您想获得自定义类型,您可以访问字段名称,如下例所示:

      {% if 'RelationField' in field.__class__.__name__ %}
          <div class="col-md-1">
          Manage object
          </div>
      {% endif %}
    

    【讨论】:

    • 这给了我一个错误,但至少它确实打印了类型:access to attribute '__class__' of 'timedelta' object is unsafe.
    【解决方案3】:

    怎么样:

    {% if {'a':1,'b':2} is mapping %}
        print "Oh Yes!!"
    {% else %}
        print "Oh No!!!"
    {% endif %}
    

    参考List of Builtin Tests

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 2012-03-24
      • 1970-01-01
      • 2021-01-13
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多