jk0*_*104 4 python jinja2 flask
有没有办法在Jinja模板中调用Python函数?该函数将获取字符串years并将其转换为列表.
years = years.replace('[', '')
years = years.replace(']', '')
years = years.split(',')
Run Code Online (Sandbox Code Playgroud)
如何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 %}
Run Code Online (Sandbox Code Playgroud)
Abh*_*pta 14
从模板中调用函数的一种方法是使用@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)
Run Code Online (Sandbox Code Playgroud)
在像footer.html这样的html文件中
<p> Copyright {{ company() }} 2005 - {{ date_now("%Y") }} </p>
Run Code Online (Sandbox Code Playgroud)
产量
Copyright ABC Pvt. Ltd. 2005 - 2015
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
如果你真的需要在模板中提供它(你可能没有),你可以添加json.loads到Jinja全局变量.
app.add_template_global(json.loads, name='json_loads')
Run Code Online (Sandbox Code Playgroud)
然后在像普通函数这样的模板中使用它.
{{ macros.pagination_widget(pagination, '.yearresults', years=json_loads(years)) }}
Run Code Online (Sandbox Code Playgroud)
小智 5
可能如下:
首先在您的main.py文件中
def myYearLister(year):
return year.INTOLISTORWHATEVER
Run Code Online (Sandbox Code Playgroud)
然后在main.py中的某个位置包含以下内容(最好在函数之后执行),以使该函数可全局访问
app.jinja_env.globals.update(myYearLister=myYearLister)
Run Code Online (Sandbox Code Playgroud)
最后,您可以像这样从模板调用或使用该函数
<div> {{ myYearLister(anything) }} </div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15126 次 |
| 最近记录: |