TurboGearsでメモ帳アプリを作る 3
前回で「新規作成画面」に入力値検証機能を組み込んだ。次は「メイン画面」に作成したファイルの一覧を表示する。
「pynote/controllers.py」を開いて、「contents_dir」ディレクトリのファイルの一覧を戻り値のディクショナリに追加する。
import os contents_dir = "contents/" class Root(controllers.RootController): @expose(template="pynote.templates.index") def index(self): return dict(files=os.listdir(contents_dir)) # 省略...
「pynote/templates/index.kid」を開いて、ファイルの一覧をリスト形式で表示する処理を追加する。
pynote/templates/index.kid
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:extends="'master.kid'"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" py:replace="''"/> <title>PyNote</title> </head> <body> <div id="pynote"> <div id="pynote_sidebar"> <!-- ファイルの一覧をリストで表示 --> <ul> <li py:for="f in files"> <a href="index?file=${f}" py:content="f">item</a> </li> </ul> </div> <div id="pynote_main"> <div id="pynote_command"> <a href="new">新規作成</a> </div> </div> </div> </body> </html>
これで「メイン画面」にアクセスすると以下のように表示される。
ここでファイルの一覧からファイル名をクリックするとエラーが表示される。何故かと言えばリンク先のURLにクエリで「file」という名前でファイル名を渡しているけど、コントローラクラスの「index」メソッドには「file」という名前の引数が定義されていないから。
なのでこれを定義して、「file」引数が渡されてきた場合はファイルを開いて画面に表示する処理を追加する。
「pynote/controllers.py」を開く。
# 指定したファイル名のファイルをcontents_dirから読み込みます。 def readText(file_name): if file_name == "": return "" f = open(contents_dir + file_name, "r") text = f.read() f.close() return text class Root(controllers.RootController): @expose(template="pynote.templates.index") def index(self, file=""): return dict( files=os.listdir(contents_dir), edit_text=readText(file)) # 省略...
これに合わせて「pynote/templates/index.kid」も変更する。
pynote/templates/index.kid
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:extends="'master.kid'"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" py:replace="''"/> <title>PyNote</title> </head> <body> <div id="pynote"> <div id="pynote_sidebar"> <ul> <li py:for="f in files"> <a href="index?file=${f}" py:content="f">item</a> </li> </ul> </div> <div id="pynote_main"> <div id="pynote_command"> <a href="new">新規作成</a> </div> <!-- テキストを表示する --> <div id="pynote_content"> <pre py:content="edit_text"> </pre> </div> </div> </div> </body> </html>