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目录所在的位置.


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部