【Python】標準テンプレートエンジン

■ はじめに

https://dk521123.hatenablog.com/entry/2018/09/22/142348

で、テンプレートエンジン「jinja2」について扱ったが、
標準でもテンプレートエンジンがあるらしいので、触れてみた。

結論

シンプルなものならいいが、ループやIFなどはないので、
他のテンプレートエンジンが使えるなら、そっちのほうがいい

■ サンプル

例1)Hello world

import string

template = string.Template('${greeting} world, ${name}')
result = template.safe_substitute(
  greeting='Hello', name='Mike')
print(result)

出力結果

Hello world, Mike

例2)外部ファイルを取り込む

import string

def generate_text_from_template(template_path, params):
  with open(template_path) as template_file:
    template = string.Template(template_file.read())
    return template.safe_substitute(params)

template_path = 'template_sample.tmpl'
params = {"greeting": "Hello", "name": "Mike"}
result = generate_text_from_template(template_path, params)
print(result)

template_sample.tmpl

${greeting} world, ${name}

出力結果

Hello world, Mike

参考文献

https://blanktar.jp/blog/2013/05/python-template.html

関連記事

Webフレームワーク 「Flask」 ~ テンプレートエンジン「jinja2」 ~
https://dk521123.hatenablog.com/entry/2018/09/22/142348