jinja2 使用教程

jinja2模板使用教程

网上很多教程都是直接copy官方文档。。。

jinja2的内置测试器的行为非常迷惑。。。iterable,mapping,string等的测试行为实际上跟python中的理解不同:

sw-office-lon-01 is an iterable: True
sw-office-lon-01 is a sequence: True
sw-office-lon-01 is a string: True

4.22 is a number: True
4.22 is an integer: False
4.22 is a float: True

65001 is a number: True
65001 is an integer: True
65001 is a float: False

{'Ethernet1': 'Uplink to core'} is an iterable: True
{'Ethernet1': 'Uplink to core'} is a sequence: True
{'Ethernet1': 'Uplink to core'} is a mapping: True

['1.1.1.1', '8.8.4.4', '8.8.8.8'] is an iterable: True
['1.1.1.1', '8.8.4.4', '8.8.8.8'] is a sequence: True
['1.1.1.1', '8.8.4.4', '8.8.8.8'] is a mapping: False

最后结论如下:

So what all of this means? Well, I suggest the following tests for each type of variable:

Number, Float, Integer - these work just as expected, so choose whatever fits your use case.

Strings - it's enough to use string test:

{{ my_string is string }}

Dictionary - using mapping test is sufficient:

Lists - this is a tough one, full check should tests if variable is a sequence but at the same time it cannot be a mapping or a string:

In some cases we know dictionary, or a string, is unlikely to appear so we can shorten the check by getting rid of mapping or string test:

{{ my_list is sequence and my list is not string }}

For the full list of available tests follow the link in References.

以上部分来自顶部的链接。

posted @ 2021-08-04 12:02  xinze  阅读(246)  评论(0编辑  收藏  举报