以下の内容はhttps://dk521123.hatenablog.com/entry/2020/01/07/212138より取得しました。


【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

関連記事

Jinja2 ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2024/10/19/000848
Jinja2 ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2024/10/18/001757
Flask ~ jinja2 ~
https://dk521123.hatenablog.com/entry/2018/09/22/142348




以上の内容はhttps://dk521123.hatenablog.com/entry/2020/01/07/212138より取得しました。
このページはhttp://font.textar.tv/のウェブフォントを使用してます

不具合報告/要望等はこちらへお願いします。
モバイルやる夫Viewer Ver0.14