2

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')
kartheek7895
  • 341
  • 1
  • 12
dipit
  • 105
  • 2
  • 5
  • 8
  • 5
    1. Please fix your indentation. 2. This is not a question about calling from HTML (which would presumably involve Ajax) but from a Jinja2 template. – Daniel Roseman Nov 24 '14 at 09:31
  • 1
    Check out the Jinja2 docs. And while you're at it, Flask docs too. – fr1tz Nov 24 '14 at 09:39

1 Answers1

4

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 %}
dpgaspar
  • 1,193
  • 8
  • 10
  • I tried your second method but it's still not working. Also isn't it supposed to be `myfunction = search.a` – dipit Nov 24 '14 at 11:32
  • I don't understand your search.a. Something is wrong with your code (identation?). This is a hit you can pass a function reference to Jinja2 and then call it on the template. If you want your html to fetch json from server, this is done on a completely different way. – dpgaspar Nov 24 '14 at 20:14