LoginSignup
10
9

More than 5 years have passed since last update.

Python3.3.1 + Bottle でWebアプリケーション(1) - テンプレートエンジンをjinja2に変更する

Last updated at Posted at 2013-09-02
app.py
from bottle import route, run
from bottle import TEMPLATE_PATH, jinja2_template as template

TEMPLATE_PATH.append("./views")

@route('/')
@route('/hello/<name>')
def greet(name="Stranger"):
    return template('hello.j2', name=name)

run(host='localhost', port=8080, debug=True, reloader=True)

ソースは上の通り(開発環境)。

  • jinja2_templateをimportする(htmlファイルのパスを指定したい場合はTEMLATE_PATHも)
  • jinja2テンプレートを返却(拡張子は何でもいいのか…?)

参考までに

hello.j2
{% extends "base.j2" %}

{% block content %}
    Hello {{ name }}! How are you?
{% endblock %}
base.j2
<html>
    <head>
        <title> Sample Bottle App </title>
    </head>
    <body>
        {% block content %} {% endblock %}
    </body>
</html>

でサーバを走らせて

% python app.py

http://localhost:8080/

http://localhost:8080/hello/hoge
にアクセスすると、デフォルトとパラメータ両方正しく画面が出力されることが確認されます。

10
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9