你非常接近,你只需要将它移到你的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目录所在的位置.