ãBottleã@viewãã³ã¬ã¼ã¿ãèªåã§å®ç¾©ãããJinja2ã
é常Bottleã使ç¨ããå ´åã¯ã使ç¨ãããã³ãã¬ã¼ãã«ä½µãã¦å¿ è¦ãªã¡ã½ããããã³ã¬ã¼ã¿ãã¤ã³ãã¼ããã¦ç¨ãããã¨ã§ãviewãã³ãã¬ã¼ãã®æç»ãé常ã«ç°¡åã«è¡ããã¨ãåºæ¥ã¾ãã
ä¾ãã°ãJinja2ãã³ãã¬ã¼ãã使ç¨ããã¡ã½ããã§viewãã³ãã¬ã¼ãã®æç»ãè¡ãå ´åã¯ä»¥ä¸ã®ããã«ãªãã¾ãã
from bottle import route, jinja2_template as template @route('/') def index(): return template('index.html', data = some_func())
ã¾ããåæ§ã®å¦çããã³ã¬ã¼ã¿ã§å®è£ ããã¨ä»¥ä¸ã®ããã«ãªãã¾ãã
from bottle import route, jinja2_view as view @route('/') @view('index.html') def index(): return dict(data=some_func())
ãã®ã¡ã½ãã群ã¯é常ã«ä¾¿å©ã§ãããç´°ããã»ããã£ã³ã°ããããã¨ããã¨ãå°ãªããªãåé¡ãçºçãã¾ãã
ä¾ãã°ããã³ãã¬ã¼ãå´ã§ä½ããã®é¢æ°ãå©ç¨ãããå ´åãjinja2.Environment
ã®globals
ã«è¿½å ãã¾ãããbottleã«ç¨æããã¦ããã¡ã½ããã§ãããå®è£
ããã®ã¯å°ã
é£ããã§ãï¼ããã¾ã§ã½ã¼ã¹ã³ã¼ããèªãã§ããªãã®ã§å¯è½ããããã¾ããï¼ã
ã¨ããããã§ãtemplateã®å±éãè¡ãviewãã³ã¬ã¼ã¿ãèªåã§å®è£ ãã¦ãã¾ãã¨ããçµè«ã«è³ãã¾ãã
ç°å¢
Bottle v0.12
Jinja2 v2.8
å®è£
æ°ããviewç¨ã®ãã¡ã¤ã«ãdecoview.pyã¨ããååã§ä½æãã以ä¸ã®ããã«ãã¾ãã
# decoview.py import functools import jinja2 env = jinja2.Environment( loader=jinja2.FileSystemLoader('./path/to/views'), autoescape = True ) env.globals.update({ 'some_func_key', some_func() }) def some_func(): return 'Called some_func!' def view(template_name): def decorator(view_func): @functools.wraps(view_func) def wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if isinstance(response, dict): template = env.get_or_select_template(template_name) return template.render(**response) else: return response return wrapper return decorator
ãã£ãããªã®ã§autoescape
ãTrue
ã«ãã¦ã¿ã¾ããã
æ°ããä½æããdecoviewãã¤ã³ãã¼ããã¦ä½¿ç¨ããã°ãjinja2ãã³ãã¬ã¼ããã¡ã¤ã«ã®ä¸ã§some_func()
ãå®è¡å¯è½ã§ãã
# index.py from bottle import route from decoview import view @route('/') @view('index.html') def index(): return {}
ä¾ãã°ä¸è¨ã®ããã«jinja2ãã³ãã¬ã¼ããå¼ã³åºãã¾ãã
<!-- index.html -->
{{ some_func_key }}
ãã£ã¨Called some_func!
ã¨ããæååã表示ããã¦ãããã¨ã¨æãã¾ãã
åè
API — Jinja2 Documentation (2.8-dev)
Jinja2 templates and Bottle | Reliably Broken