简体   繁体   中英

Call a Python function from a Jinja template

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 %}

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

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)) }}

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM