Reputation: 31
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?
Upvotes: 3
Views: 15445
Reputation: 6575
Jinja2 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.com/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 command on backend and returns the result.
Upvotes: 4