python webpy のテンプレート処理を使ってみる



JavaのVelocityを使ったことがあるので、webpy  のテンプレート処理も
便利そうだなと思い試してみました。

1./var/www/webpy/templatesフォルダを作成。

2.その中にhello.htmlを作成
内容はこんな感じ


$def  with  (name)

$if  name:
        Hello  $name.
$else:
        Hello  world.



※インテンドはスペース4つで。


3.code.pyにテンプレート読み込みロジックを追加。

render  =  web.template.render('/var/www/webpy/templates/')



4.code.pyにURLを追加

urls  =  (
        '/',  'index',
        '/faq',  'faq'
        '/hello',  'hello'
)


5.helloクラスを追加

class  hello:
def  GET(self):
        web.header("Content-Type",  "text/html;  charset=utf-8")
        name  =  'Bob'
        print  render.hello(name)



コレで、
http://exsample.com/webpy/code.py/hello
にアクセスすると
Hello  Bob.  
と表示されるはず。


最終的なcode.pyはコチラ

import  web

urls  =  (
        '/',  'index',
        '/faq',  'faq'
        '/hello',  'hello'
)

main  =  web.wsgifunc(web.webpyfunc(urls,globals()))
render  =  web.template.render('/var/www/webpy/templates/')

class  index:
        def  GET(self):
                web.header("Content-Type",  "text/html;  charset=utf-8")
                print  "hello,  world!"


class  faq:
        def  GET(self):
        web.header("Content-Type",  "text/html;  charset=utf-8")
        print  "module  faq  was  called!"

class  hello:
        def  GET(self):
        web.header("Content-Type",  "text/html;  charset=utf-8")
        name  =  'Bob'
        print  render.hello(name)


if  __name__  ==  '__main__':
        web.run(urls,  globals())



もどる