【问题标题】:Call a Python function from a Jinja template从 Jinja 模板调用 Python 函数
【发布时间】:2015-07-30 15:02:41
【问题描述】:

有没有办法在 Jinja 模板中调用 Python 函数?该函数将只获取字符串years 并将其转换为列表。

years = years.replace('[', '')
years = years.replace(']', '')
years = years.split(',')

如何在下面的模板中调用years

{% extends "base.html" %}
{% import "_macros.html" as macros %}

{% block title %}Year Results{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Year Search Results</h1>
</div>
<ul class=entries>
    {% for entry in entries %}
    <li><h3><a href="{{ url_for('main.grantinfo', applid=entry.appl_id) }}">{{ entry.appl_id }} : {{ entry.project_title }}</a></h3>
    <br>
    {% else %}
    <li><em>No entry here</em>
    {% endfor %}
</ul>

{% if pagination %}
<div class="pagination">
    {{ macros.pagination_widget(pagination, '.yearresults', years=years) }}
</div>
{% endif %}
{% endblock %}

【问题讨论】:

    标签: python flask jinja2


    【解决方案1】:

    从模板中调用函数的一种方法是使用@app.context_processor 装饰器。

    在 main.py 等 python 文件中

    @app.context_processor
    def my_utility_processor():
    
        def date_now(format="%d.m.%Y %H:%M:%S"):
            """ returns the formated datetime """
            return datetime.datetime.now().strftime(format)
    
        def name():
            """ returns bulshit """
            return "ABC Pvt. Ltd."
    
        return dict(date_now=date_now, company=name)
    

    在像footer.html这样的html文件中

    <p> Copyright {{ company() }} 2005 - {{ date_now("%Y") }} </p>
    

    输出

    Copyright ABC Pvt. Ltd. 2005 - 2015
    

    【讨论】:

    • 在您的示例中,company=name 可以直接为company="ABC Pvt. Ltd.",然后在footer.html 中只是{{ company }}。但是,如果稍后需要扩展/复杂化它,那么您的示例很棒,只是说如果它只是返回一些常量字符串(对于未来的困惑读者),它不必调用函数。
    • 我意识到这个问题被标记为烧瓶,但谷歌没有。所以应该说这是一个 Flask 特定的答案。对其他人没有帮助。
    【解决方案2】:

    years 似乎是一个 JSON 列表,因此请使用 json.loads 对其进行解析,而不是手动剥离和拆分字符串。 years 似乎是从视图发送到模板的变量,所以只需在视图中进行处理即可。

    years = json.loads(years)
    # years string "[1999, 2000, 2001]"
    # becomes list [1999, 2000, 2001]
    # without parsing the string manually
    return render_template('years.html', years=years)
    

    如果您确实需要在模板中提供此功能(您可能不需要),您可以将 json.loads 添加到 Jinja 全局变量中。

    app.add_template_global(json.loads, name='json_loads')
    

    然后像普通函数一样在模板中使用它。

    {{ macros.pagination_widget(pagination, '.yearresults', years=json_loads(years)) }}
    

    【讨论】:

      【解决方案3】:

      可能如下:

      首先在你的 main.py 文件中

      def myYearLister(year):
          return year.INTOLISTORWHATEVER
      

      然后在 main.py 中的某处包含以下内容(最好在函数之后执行)以使函数全局可访问

      app.jinja_env.globals.update(myYearLister=myYearLister) 
      

      最后,您可以调用或使用模板中的函数

      <div> {{ myYearLister(anything) }} </div>
      

      【讨论】:

        猜你喜欢
        • 2021-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多