2015-02-07 115 views
0

我一直在尝试阅读与Flask和Jinja的文本文件,但使用for循环,我一直在遇到麻烦。我的代码如下:Jinja错误返回关于For循环

{% 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 %} 

唯一的问题是,它返回一个错误:

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'.

我发现,正是这个问题引起:

fileNameOpen = open(fileNamesIterator, "r")
fileLines = fileName.readlines()

但不该” t我能够在for声明之后但在endfor声明之前做其他Python语句吗?

任何想法?

解决方案:神社的Python和大部分的工作需要做出来的模板

回答

2

神社是的Python(如果你需要能够写入任意Python在你的模板中,你会更好地使用Mako)。相反,你需要做在Python的工作,将结果传递到神社:

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) 

那么你的模板可以只是:

{% 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 %}