要在Tornado模板中遍歷一個二維數組,你可以使用Tornado的模板語法來實現迭代和顯示數組中的每個元素。
以下是一個示例,演示如何在Tornado模板中遍歷和顯示二維數組的內容:
template.html:
<!DOCTYPE html>
<html>
<head><title>Tornado Template Example</title>
</head>
<body><table>{% for row in array %}<tr>{% for col in row %}<td>{{ col }}</td>{% end %}</tr>{% end %}</table>
</body>
</html>
app.py:
import tornado.ioloop
import tornado.webclass TemplateHandler(tornado.web.RequestHandler):def get(self):array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 二維數組示例self.render("template.html", array=array)if __name__ == "__main__":app = tornado.web.Application([(r"/", TemplateHandler)])app.listen(8888)tornado.ioloop.IOLoop.current().start()
在這個示例中,我們創建了一個名為TemplateHandler
的請求處理器。在get
方法中,我們初始化一個二維數組array
。然后,我們使用self.render
方法來渲染template.html
模板,并將數組傳遞給模板中的array
變量。
在template.html
中,我們使用Tornado的模板語法來進行迭代。通過{% for row in array %}
開始一個外部循環,遍歷數組中的每一行。在內部循環中,{% for col in row %}
遍歷當前行的每個元素。通過{{ col }}
將當前元素顯示到視圖中。
當你訪問http://localhost:8888/
時,Tornado將渲染模板并在瀏覽器中顯示二維數組的內容。每個元素將顯示在HTML表格的單元格中。
注意:上述示例中,模板文件template.html
應該與app.py
在同一目錄中。如果不是,在self.render
方法中可以指定模板文件的路徑。例如:self.render("templates/template.html", array=array)
。