2017-11-04 8 views
0

JSPまたはJadeのようなタグを使って自分のHTMLテンプレートを設計し、それからPythonのデータを渡して完全なHTMLページを生成させたいのですが、pythonでHTMLテンプレートからHTMLを生成しますか?

私はDOMのように、Python側でドキュメントを構築したくありません。データのみがページとページのテンポラリに、データがどのようにレイアウトされるかが決まります。

私は結果のページをHTTPで配信したくないので、HTMLファイルのみを生成します。

可能ですか?

UPDATE

私はJinja2のを見つけましたが、私は奇妙なboilerplate requirementsを持っています。例えば、彼らはパッケージyourapplicationが見つからないことを言いながら、私は

env = Environment(
    loader=PackageLoader('yourapplication', 'templates'), 
    autoescape=select_autoescape(['html', 'xml']) 
) 

で環境を作成します。私はloaderパラメータを削除した場合、それは

no loader for this environment specified 
を言っライン

template = env.get_template('mytemplate.html') 

に文句を言う私は、ディスクからテンプレートを読み込むと、余分なものなしに、変数を移入することはできますか?

答えて

1

だけFileSystemLoaderを使用します。

import os 
import glob 
from jinja2 import Environment, FileSystemLoader 

# Create the jinja2 environment. 
current_directory = os.path.dirname(os.path.abspath(__file__)) 
env = Environment(loader=FileSystemLoader(current_directory)) 

# Find all files with the j2 extension in the current directory 
templates = glob.glob('*.j2') 

def render_template(filename): 
    return env.get_template(filename).render(
     foo='Hello', 
     bar='World' 
    ) 

for f in templates: 
    rendered_string = render_template(f) 
    print(rendered_string) 

example.j2

<html> 
    <head></head> 
    <body> 
     <p><i>{{ foo }}</i></p> 
     <p><b>{{ bar }}</b></p> 
    </body> 
</html 
関連する問題