Import a Python module into a Jinja template?

前端 未结 4 1032
独厮守ぢ
独厮守ぢ 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条回答
  •  旧时难觅i
    2020-12-13 02:15

    You can export all of the symbols available in a module by providing the modules __dict__ as a parameter to the jinja template render method. The following will make available functions and types of __builtin__, inspect and types module to the template.

    import __builtin__
    import inspect
    import types
    
    env=RelEnvironment()
    template = env.get_template(templatefile)
    
    export_dict={}
    export_dict.update(__builtin__.__dict__)
    export_dict.update(types.__dict__)
    export_dict.update(inspect.__dict__)
    
    result=template.render(**export_dict)
    

    Within template, to use a function of the exported modules similar to the following:

    {%- for element in getmembers(object) -%}
    {# Use the getmembers function from inspect module on an object #}
    {% endfor %}
    

提交回复
热议问题