Call a Python function from a Jinja template
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)) }}
How to import and call a Python function in a Jinja template?
First approach. If you want to pass function only to one template, you can pass function to template as variable. For example
render_template("index.html", func=f)
And then call it in template, {{ func(1) }}
If you want function or variable accessible in all templates (globally). You can add them during flask application initialization to app.jinja_env.globals
dict, like:app.jinja_env.globals['func'] = f
Call function with arguments from user input in Python3 Flask Jinja2 template
The code you use is a brief description of the exclusive use within a directly defined template.
To use a custom function within a template used by render_template
, you have to add it to the dictionary globals of the jinja environment.
from flask import Flask
from flask import render_template, request
def clever_function(value):
return value**2
app = Flask(__name__)
app.jinja_env.globals.update(clever_function=clever_function)
@app.route('/form')
def form():
return render_template('form.html')
@app.route('/data', methods=['POST'])
def data():
return render_template('data.html', form_data=request.form)
From now on, this function can be called in every template which is loaded and called up with this environment.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p>Result: {{ clever_function(form_data.get('random', 0) | int) }}</p>
</body>
</html>
Please keep in mind that the defined function must accept parameters if you want to call it up with any.
Errors have also crept in when using the namespace object. You should take another look at the documentation for the assignments in jinja2.
Here is a small example based on your code.
{% set ns1 = namespace(random=0) %}
{% for k,v in form_data.items() %}
{% if k == 'random' %}
{% set ns1.random = v | int %}
{% endif %}
{% endfor %}
<p>Value is {{ns1.random}}</p>
How to call a python function with no parameters in a jinja2 template
Summarizing the comments into an answer:
The ability to call functions by adding it to filters isn't really the correct way of going about this since (as Wooble pointed out) I'm not looking to filter anything.
Instead the function just needs to be added to the template_env.globals:
template_globals.filters['ctest'] = ctest
How can I call a python function on the Flask server using a Jinja2 html template?
After more googling I figured it out. If anyone is curious, I took Daniel's advice and restructured the html. However, that didn't completely fix it. The action sytanx was:
<form action='/sign_in_check' method="POST">
and then the server handled it like so:
@app.route('/sign_in_check', methods = ['GET', 'POST'])
def sign_in_check():
if request.method == 'POST':
I had to make sure the function accepted POST or GET. Also, unlike django, the request syntax for flask is a bit different. Like so,
driver_first_name = request.form.get('driver_first_name')
Hope this helps anyone else that had similar problems.
calling python function within saltstack sls
First, You are not getting a dict back, you are getting a tuple back. there is a big difference. second {% set app,no = salt['emod.app_instance_match'](app) %}
is exactly what you should be using. that will split the variables into two parts app
and no
. I should note sometimes using salt-ssh actually makes debugging things in salt harder. I would suggest installing a local minion to at least test these basic things.
Here is an example using your own code. I named it epp instead of emod.
[root@salt00 tests]# cat tests.sls
{% set x,y = salt['epp.app_instance_match']('test-14') %}
x: {{x}}
y: {{y}}
[root@salt00 tests]# salt-call slsutil.renderer salt://tests/tests.sls default_render=jinja
local:
----------
x:
test-14
y:
0
[root@salt00 tests]# cat ../_modules/epp.py
from re import sub, match, search
def app_instance_match(app):
instance_no = 0
m = search('^(.*)(-)(\d)$', app)
if m is not None:
app = m.group(1)
instance_no = int(m.group(3))
return app, instance_no
The second thing is you might want to look at https://docs.saltproject.io/en/latest/topics/jinja/index.html#regex-search which is already a regex search.
And third. Your regex looks off. ^
and $
don't really work well with single strings. which would explain why test-14
didn't come back as ('test',1)
but instead came back as ('test-14',0)
I'm thinking you want '(.*)-(\d*)'
as your real regex. which will return ('test',14)
for test-14
Related Topics
Random State (Pseudo-Random Number) in Scikit Learn
Python: Best Way to Add to Sys.Path Relative to the Current Running Script
Comparing Python Dictionaries and Nested Dictionaries
Find First Sequence Item That Matches a Criterion
Importing Pyspark in Python Shell
Can't Install New Packages for Python (Python 3.9.0, Windows 10)
Scipy: Savefig Without Frames, Axes, Only Content
Running Infinite Loops Using Threads in Python
Catching an Exception While Using a Python 'With' Statement
Removing a List of Characters in String
Heapq with Custom Compare Predicate
What Limitations Have Closures in Python Compared to Language X Closures
Calculating Difference Between Two Rows in Python/Pandas
What Is the _Dict_._Dict_ Attribute of a Python Class