Skip to content

Instantly share code, notes, and snippets.

@advanceboy
Created January 12, 2019 18:23
Show Gist options
  • Save advanceboy/688d26e67debfd806058e94653872757 to your computer and use it in GitHub Desktop.
Save advanceboy/688d26e67debfd806058e94653872757 to your computer and use it in GitHub Desktop.
Flask + jinja でレイアウトの指定 (extends タグ) のテンプレートを ソースコード文字列 で指定するサンプル (ソースコードのライセンスは CC0)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Give the template inheritance of the `extends` tag as a template source string.
"""
from flask import Flask, render_template_string
from datetime import datetime
app = Flask(__name__)
@app.before_first_request
def define_layout():
layout_template = '''<!doctype html>
<html>
<head><title>{{title}}</title></head>
<body>
<h1>{{title}}</h1>
{% block content %}{% endblock %}
</body>
</html>'''
copyright_template = '<div>foo bar (c)</div>'
app.jinja_env.globals['layout'] = app.jinja_env.from_string(layout_template)
app.jinja_env.globals['copyright'] = app.jinja_env.from_string(copyright_template)
@app.route('/')
def index():
template = '''{% extends layout %}
{% block content %}
<p>Current Time: {{nowtime}}</p>
{% include copyright %}
{% endblock %}
'''
return render_template_string(template, title='Index', nowtime=datetime.now())
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment