tornadoテンプレート使用

2961 ワード

1、テンプレートパスの指定
app = tornado.web.Application(
        handlers=[(r'/', IndexHandler), (r'/poem', PoemPageHandler)],
        template_path=os.path.join(os.path.dirname(__file__), "templates")
    )

まず,Applicationオブジェクトのinitメソッドにtemplate_を渡した.pathパラメータ、template_pathパラメータはTornadoがテンプレートファイルをどこで探しているかを教えます.
2、テンプレートファイルの作成index.htmlはtemplatesディレクトリの下に格納されます.


      
    
        

Hello,Stranger!

demo2.html


          
    
        

{{ name }}

{{ age }}

{{ sex }}


3、テンプレートの使用self.render('index.html') self.render('demo2.html',name=' ',age=100,sex='man')
4、テンプレート構文
じゅうてんしき
任意のPython式を二重括弧に入れることができます.Tornadoは、式の計算結果値の文字列を出力に挿入します.


          
    
        

{{ 10+20 }}

{{ ‘hello’[2:] }}

{{ ','.join([str(x*x) for x in range(10)])}}


せいぎょりゅうぶん
Python条件とループ文は、Tornadoテンプレートで使用でき、if、for、while、tryをサポートします.構文:
{%    %}
        
{% end %}
   {% for book in books %}
        
  • {{ book }}
  • {% end %} {% if True %}

    This True.

    {% else %}

    This False.

    {% end %}

    5、テンプレートでの関数の使用
    Tornadoは、すべてのテンプレートでデフォルトでいくつかの便利な関数を提供しています.
    escape(s)
         s  &、      HTML  。
    
    url_escape(s)
      urllib.quote_plus     s     URL    。
    
    json_encode(val)
     val   JSON  。(     ,     json  dumps     。                           。)
    
    squeeze(s)
         s,                 。
    

    6、静的ファイルの使用
    静的パスの設定
    アプリケーションクラスのコンストラクション関数にstatic_という名前を渡すpathのパラメータは、Tornadoがファイルシステムの特定の場所から静的ファイルを提供することを示す.
    app = tornado.web.Application(
        handlers=[(r'/', IndexHandler), (r'/poem', MungedPageHandler)],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=True
    )
    

    これで、staticディレクトリの下で静的ファイルが読み込まれます.
    静的ファイルの使用
    Tornadoテンプレートモジュールは、static_urlという関数を提供し、staticディレクトリの下のファイルのURLを生成します.例えばstaticディレクトリの下のstyleを使用する.cssファイル.
    
    

    static_url関数は、/static/style.css?v=ab12、すなわち、
    
    
    static_url関数は、ファイルの内容に基づくhash を作成します.URLの末尾に追加( v).このhash値は、以前のキャッシュ・バージョンではなく、ブラウザが常に最新のファイルをロードしていることを保証します.アプリケーションの開発段階でも、本番環境に導入して使用しても、ユーザーが静的なコンテンツを見るためにブラウザ・キャッシュを消去する必要がないため、非常に役立ちます.static_url関数を使用して静的なコンテンツを生成することに注意してください.ファイルパスは、hrefプロパティがアドレスを参照しているため、{{}}で囲まなければなりません.