有没有办法在 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 %}
最佳答案
从模板中调用函数的方法是使用 @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
关于python - 从 Jinja 模板调用 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31727367/