admin管理员组文章数量:1398174
I'm hacking a cms-like system that use Jinja2 and Javascript in frontend and Python in backend.
I implemented some Python functions on backend that do stuff on database.
I want to launch that functions from HTML pages, so i used Jinja2.
The problem is that the snippets {% %}
and {{ }}
are always parsed and processed when HTML is loaded.
I want to execute that functions when I click a button or a link.
How could I make it works?
I'm hacking a cms-like system that use Jinja2 and Javascript in frontend and Python in backend.
I implemented some Python functions on backend that do stuff on database.
I want to launch that functions from HTML pages, so i used Jinja2.
The problem is that the snippets {% %}
and {{ }}
are always parsed and processed when HTML is loaded.
I want to execute that functions when I click a button or a link.
How could I make it works?
Share Improve this question edited May 20, 2016 at 13:23 Mauro Baraldi 6,5752 gold badges35 silver badges46 bronze badges asked May 20, 2016 at 12:32 frapolfrapol 311 gold badge1 silver badge2 bronze badges 2- 2 Its not trivial... You CANNOT execute a function in python through jinja from the front end. You need to create an endpoint in python, something like: 'mydomain./api/function-i-need-to-call' and then from the client side have the js just hit that endpoint – Javier Buzzi Commented May 20, 2016 at 12:59
- What's wrong with AJAX? – Andrejs Cainikovs Commented May 20, 2016 at 14:32
1 Answer
Reset to default 4Jinja2 is a template engine. You are wrong about its use.
You could create a small app in some lightweight web framework, like Flask or Bottle, and route some ajax routes to expected methods.
Here is an example using Flask:
backend.py
import os
from json import dumps
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template('cmd.html')
@app.route("/cmd")
def cmd():
osname = os.uname()[3]
print(osname)
return dumps({'name': osname})
if __name__ == "__main__":
app.run()
As described in docs, templates must be in a folder called template
inside the project folder.
cmd.html
<html>
<head>
<script src="https://ajax.googleapis./ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
function cmd(){
$.ajax({
type: "GET",
url: "http://0.0.0.0:5000/cmd",
success: function (data) {
$("#result").html("dfsdfds")
},
});
}
</script>
</head>
<body>
<a href="#" onclick="return cmd();">Item</a>
<div id="result"></div>
</body>
</html>
To execute it just run python backend.py
. Open your browser and go to http://127.0.0.1:500
The app runs a mand on backend and returns the result.
本文标签: javascriptJinja2call function on clickStack Overflow
版权声明:本文标题:javascript - Jinja2 : call function on click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744114264a2591436.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论