300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python分支语句中if和else必须同时出现吗_python – if else在jinja2中分支

python分支语句中if和else必须同时出现吗_python – if else在jinja2中分支

时间:2023-10-24 20:26:24

相关推荐

python分支语句中if和else必须同时出现吗_python – if else在jinja2中分支

你非常接近,你只需要将它移到你的Python脚本中.所以你可以像这样定义一个谓词:

def short_caption(someitem):

return len(someitem) < 60

然后通过将其添加到’tests’字典中将其注册到环境中:

your_environment.tests["short_caption"] = short_caption

你可以像这样使用它:

{% if item[0] is short_caption %}

{# do something here #}

{% endif %}

有关更多信息,请参阅custom tests上的jinja文档

(你只需要这样做一次,我认为无论你是在开始渲染模板之前还是之后都这样做,文档都不清楚)

如果您还没有使用环境,可以像这样实例化它:

import jinja2

environment = jinja2.Environment() # you can define characteristics here, like telling it to load templates, etc

environment.tests["short_caption"] = short_caption

然后通过get_string()方法加载模板:

template = environment.from_string("""your template text here""")

template.render(items=links).encode('utf-8')

最后,作为旁注,如果您使用文件加载器,它允许您进行文件继承,导入宏等.基本上,您只需保存现在的文件并告诉jinja目录所在的位置.

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。