** Note that I researched the template engine in Python. ** **
So I tried Jinja2. The origin of the name is template ⇒ temple ⇒ shrine. ‥I see.
The environment is Sakura VPS (CentOS)
yum install python-pip (only if you don't have pip yet)
pip install jinja2
Configure Apache so that Python works as CGI.
vi /etc/httpd/conf/httpd.conf
Change 2 places written in httpd.conf with vi editor etc.
httpd.conf
1)
<Directory "/var/www/html">
Options Indexes FollowSymLinks
↓ Added ExecCGI
Options Indexes FollowSymLinks ExecCGI
</Directory>
2)
#AddHandler cgi-script .cgi
↓ Uncomment and.py added
AddHandler cgi-script .cgi .py
After saving the settings, restart Apache.
service httpd restart
html:hello.tpl.html(UTF-8)
<html>
<body>
Welcome,{{ shop }}is.
<hr>
<ul>
{% for food in foods %}
<li>{{ loop.index }}: {{ food.name }} - {{ food.price }}Circle</li>
{% endfor %}
</ul>
</body>
</html>
All Python source files are written in UTF-8, and the permissions after uploading are 755 (give execute permission). Also, the following output is required before outputting HTML. (If you forget it, an error will occur immediately)
print "Content-Type: text/html\n";
hello.py(UTF-8)
#!/usr/bin/python
# -*- coding: utf-8 -*-
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('./', encoding='utf8'))
tpl = env.get_template('hello.tpl.html')
foods = []
foods.append({'name':u'ramen', 'price':400})
foods.append({'name':u'Fried rice', 'price':500})
foods.append({'name':u'Tianjin rice', 'price':600})
html = tpl.render({'shop':u'Gokuken', 'foods':foods})
print 'Content-Type: text/html; charset=utf-8\n'
print html.encode('utf-8')
After that, access hello.py from your browser and check.
(・ O ・ ゞ Ijo.
jinja2 | it-note 1.0 document http://maman-it-information.readthedocs.org/ja/latest/src/python/jinja2/jinja2.html
Official Python documentation http://jinja.pocoo.org/docs/dev/
Recommended Posts