Reputation: 151
Is there a way to call a Python function inside a Jinja template? The function will just take the string years
and turn it into a list.
years = years.replace('[', '')
years = years.replace(']', '')
years = years.split(',')
How can I call this on years
in the template below?
{% 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 %}
Upvotes: 6
Views: 31115
Reputation: 322
It is possible as follows:
First in your main.py file
def myYearLister(year):
return year.INTOLISTORWHATEVER
then include the following somewhere in main.py( better do it after the function) in order to make the function globally accessible
app.jinja_env.globals.update(myYearLister=myYearLister)
Lastly, you can call or use the function from your template as such
<div> {{ myYearLister(anything) }} </div>
Upvotes: 8
Reputation: 4166
A way to call functions from within the template is using @app.context_processor
decorator.
In python file like main.py
@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)
In html file like footer.html
<p> Copyright {{ company() }} 2005 - {{ date_now("%Y") }} </p>
Output
Copyright ABC Pvt. Ltd. 2005 - 2015
Upvotes: 21
Reputation: 127190
years
appears to be a JSON list, so use json.loads
to parse it rather than stripping and splitting strings manually. years
appears to be a variable sent from the view to the template, so just do the processing in the view.
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)
If you really need to make this available in templates (you probably don't), you can add json.loads
to the Jinja globals.
app.add_template_global(json.loads, name='json_loads')
Then use it in a template like a normal function.
{{ macros.pagination_widget(pagination, '.yearresults', years=json_loads(years)) }}
Upvotes: 10