pythonでテンプレートエンジンを利用する
バッテリー同梱のpythonはテンプレートエンジンも標準に組み込まれている。
下記の通り利用することができる。
1 2 3 | import string t = string.Template('Hello ${name}!') t.substitute({'name': 'Python'}) |
しかし、このテンプレートはとてもシンプルな変換しかできない。
単純なキーワード置換のみ。
そこで簡単に導入できて、ループや条件分岐ができるテンプレートを利用する。
bottle
https://bottlepy.org/docs/dev/
テンプレートエンジンは、bottleの一部の機能。
それでも、十分に高性能なテンプレートが利用できる。
インラインで変換
1 2 3 4 5 6 7 8 9 10 11 12 13 | import bottle bottle.template(''' {{ msg }} % for item in items: {{ item['no'] }} : {{ item['name'] }} % end ''', { 'msg': 'test bottle', 'items': ( {'no': '1', 'name': 'AAA'}, {'no': '2', 'name': 'BBB'}, ) }) |
ファイルのテンプレートを読んで、ファイルに出力する
template.tmpl
1 2 3 4 | {{ msg }} % for item in items: {{ item['no'] }} : {{ item['name'] }} % end |
1 2 3 4 5 6 | import bottle import codecs data = {} with codecs.open('output.txt', 'w', 'utf-8') as w: with codecs.open('template.tmpl', 'r', 'utf-8') as r: w.write(bottle.template(r.read(), data)) |
まとめ
bottleを使うと、一般的なテンプレート機能が使える。
bottleは%の行の変換が適切に行われるので、メールなどのテキストテンプレートに問題なく使える(テンプレートエンジンによっては、余分な改行やスペースが入ってしまったりする)。
また、テンプレートエンジンはbottleの一つの機能でしかなく、もっといろいろなことができる。
スタンドアロンサーバになったりするようだ。
これらも活用できれば、ツールの幅がぐっと広がりそうだ。
- BOM付きUTF-8からBOMを除去するpython
- jythonのヒープメモリ設定
- Kotlin1.2.50がリリースされていた
- macOSをHigh Sierraに更新した。スクリプト実行環境のバージョンは変わったのか
- macOSをMojaveに更新した。スクリプト実行環境のバージョンは変わったか
- pathlib.Pathを調べる
- pyenvでpython環境をインストール
- pyenvとvirtualenvでpython環境を構築
- python unpack
- python3で数値のlistを文字列のlistに変換