Reputation: 119
I have been trying to read text files with Flask and Jinja but using for loops, I have been running into trouble. My code is below:
{% for fileNamesIterator in fileNames
fileNameOpen = open(fileNamesIterator, "r")
fileLines = fileName.readlines() %}
<div id="{{ fileNamesIterator[:len(fileNamesIterator)-4] }}" class="title">Title: {{ fileLines[2] }}</div>
<div class="author">Author: {{ fileLines[1] }}</div>
<div class="date">Date Posted: {{ fileLines[0] }}</div>
<br><br>
<div class="mainText"> {{ fileLines[3] }} <br> {{ fileLines[4] }}
</div>
<hr>
{% fileLines.close()
endfor %}
The only problem is that it is returning an error:
TemplateSyntaxError: Encountered unknown tag 'fileLines'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
I found that it is this causing the problem:
fileNameOpen = open(fileNamesIterator, "r")
fileLines = fileName.readlines()
But shouldn't I be able to do other python statements after for
statement but before the endfor
statement?
Any ideas?
Solution: Jinja is not Python and most of the work needs to be done out of the template
Upvotes: 0
Views: 794
Reputation: 159905
Jinja is not Python (if you need to be able to write arbitrary Python in your templates you will do better with Mako). Instead, you need to do the work in Python and pass the results to Jinja:
data = []
for file_name in file_names:
with open(file_name, 'r') as f:
file_lines = f.readlines()
data.append({
"id": file_name[:len(file_name) - 4],
"title": file_lines[2],
"author": file_lines[1],
"date": file_lines[0],
"content": file_lines[3:5]
})
return render_template("template.html", articles=data)
Then your template can just be:
{% for article in articles %}
<div id="{{ article.id }}" class="title">Title: {{ article.title }}</div>
<div class="author">Author: {{ article.author }}</div>
<div class="date">Date Posted: {{ article.date }}</div>
<br><br>
<div class="mainText"> {{ article.content[0] }} <br> {{ article.content[1] }}
</div>
<hr>
{% endfor %}
Upvotes: 2