Template クラスはstringモジュールに含まれている簡単なテンプレートエンジン機能を持ったクラスです。
基本的な使い方
ディレクトリ構造(webアプリ)
test(配置する場所は任意)
├server.py (サーバー接続ファイル 説明省く)
└cgi-bin
└test.py
└tmp
└test.tmpl
置換する値(文字列)を設定するには substitute メソッドの引数に辞書を渡します。
from string import Template
from os import path
import io
import sys
#テンプレートファイルへの値にマルチバイト文字列を設定した場合の文字化けを防止
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
#テンプレートファイルの読み込み
f = open(path.join(path.dirname(__file__), 'tmp/test.tmpl'), encoding='utf-8')
t = Template(f.read())
#テンプレートファイルへの値(文字列)を設定
a = t.substitute({'name1':'山田', 'name2':'太郎'})
print('Content-type: text/html; charset=UTF-8\n')
print(a)
テンプレートファイルの ${~} の箇所が置換されます。
<html>
<body>
<p>こんにちわ、${name1} ${name2}さん</p>
</body>
</html>
● 表示
こんにち、山田 tarouさん
エンコードについて
from string import Template
from os import path
import io
import sys
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
#テンプレートファイルの読み込み
f = open(path.join(path.dirname(__file__), 'tmp/test.tmpl'), encoding='utf-8')
t = Template(f.read())
#テンプレートファイルへ値を設定
a = t.substitute({'name1':'山田', 'name2':'太郎'})
print('Content-type: text/html; charset=UTF-8\n')
print(sys.getdefaultencoding())
print(sys.stdout.encoding) #出力時のエンコード
6行目でデフォルトエンコードを「utf-8」にしています。
この設定をしていなければブラウザの表示は文字化けします。
● 表示
utf-8 utf-8
6行目を記載していない場合は出力のエンコードが「utf-8」ではなく「cp932」となりました。
● 表示
utf-8 cp932