Call python function using HTML

强颜欢笑 提交于 2019-12-18 09:37:06

问题


I have a function in python that displays a list of names.

def search():
    with open('business_ten.json') as f:
    data=f.read()
    jsondata=json.loads(data)


    for row in jsondata['rows']:
        #print row['text']
        a=str(row['name'])

        print a 
        return a

search()

I am trying to call this function in an HTML file using Flask

{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
    <h2>Welcome to the Rating app<h2>
    <h3>This is the home page for the Rating app<h3>
</div>
<body>
    <p>{{ search.a }}</p>
</body>
{% endblock %}

My routes file is as follows:

from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello gugugWorld!'
@app.route('/crawl')
def crawl():
    return render_template('crawl.html')

回答1:


There are many ways to do this:

1 - You can register a new Jinja2 filter

2 - You can pass your function as a Jinja2 parameter (This one is easier)

For method 2:

@app.route('/crawl')
def crawl():
    return render_template('crawl.html', myfunction=search)

On the template call the parameter has a function

{% extends "layout.html" %}
{% block content %}
<div class="jumbo">
<h2>Welcome to the Rating app<h2>
<h3>This is the home page for the Rating app<h3>
</div>
<body>
 <p>{{ myfunction() }}</p>
</body> 
{% endblock %}


来源:https://stackoverflow.com/questions/27101508/call-python-function-using-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!