Reputation: 93
I am trying to print a list of tuples into my html Flask template, but I am getting this error:
self.name, self.filename)
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'
I get a 500 Internal Server Error when I put the localhost
address in my browser
How can I print my data onto the browser?
CODE: eslJobs.py
from flask import Flask, render_template
import bs4 as bs
import urllib.request
app = Flask(__name__)
@app.route('/')
def chinaJobs():
sauce = urllib.request.urlopen('http://www.eslcafe.com/jobs/china/').read()
soup = bs.BeautifulSoup(sauce, 'html.parser')
dl = soup.dl
chinaAds = []
china = []
for words in dl.find_all('a'):
links = words.get('href')
link_text = words.text
if 'university' in link_text.lower():
chinaAds.append([links, link_text])
if 'college' in link_text.lower():
chinaAds.append([links, link_text])
for ad in chinaAds:
china.append(tuple(ad))
return render_template("eslJobs.html", china=china)
if __name__ == "__main__":
app.run()
CODE: eslJobs.html
<!DOCTYPE html>
<html>
<head>
<title>ESL Jobs</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bootstrap.min.css') }}">
</head>
<body>
<div class="page-header">
<h1>College & University ESL Jobs</h1>
</div>
<ul class="list-group">
{% for href, caption in {{ china }}: %}
<li class="list-group-item"><a href="{{ href }}">{{ caption }}</a> </li>
{% endfor %}
</ul>
</body>
</html>
Upvotes: 2
Views: 5943
Reputation: 10951
I think you need to fix this line:
{% for href, caption in {{ china }}: %}
to
{% for href, caption in china %}
Bonus:
This code
for words in dl.find_all('a'):
links = words.get('href')
link_text = words.text
if 'university' in link_text.lower():
chinaAds.append([links, link_text])
if 'college' in link_text.lower():
chinaAds.append([links, link_text])
for ad in chinaAds:
china.append(tuple(ad))
can all be optimized to:
for words in dl.find_all('a'):
links = words.get('href')
link_text = words.text
link_lower = link_text.lower()
if ('university' in link_lower) or ('college' in link_lower):
chinaAds.append((links, link_text))
Then just render chinaAds
:
#fix indentation of your return statement, on your actual code
#it seems belonging to the for loop
return render_template("eslJobs.html", china=chinaAds)
Upvotes: 2
Reputation: 2393
See the For
usage in jinja
document.
<h1>Members</h1>
<ul>
{% for user in users %}
<li>{{ user.username|e }}</li>
{% endfor %}
</ul>
Therefore, you don't need the double brace in your template where inside a {% %}
, you can just delete it.
{% for href, caption in china : %}
<li class="list-group-item"><a href="{{ href }}">{{ caption }}</a> </li>
{% endfor %}
In your python script, there is an indentation error, that prevent you from getting the full list.
for ad in chinaAds:
china.append(tuple(ad))
return render_template("eslJobs.html", china=china)
Upvotes: 1