Import a Python module into a Jinja template?

前端 未结 4 1038
独厮守ぢ
独厮守ぢ 2020-12-13 02:03

Is it possible to import a Python module into a Jinja template so I can use its functions?

For example, I have a format.py file that contains metho

4条回答
  •  没有蜡笔的小新
    2020-12-13 02:23

    Just pass the function into the template, like so

    from dates.format import timesince
    your_template.render(timesince)
    

    and in the template, just call it like any other function,

    {% macro time(mytime) %}
        {{ timesince(mytime) }}
    {% endmacro %}
    

    Functions are first-class citizens in python, so you can pass them around just like anything else. You could even pass in a whole module if you wanted.

提交回复
热议问题