簡體   English   中英

將Python CGI用於大型HTML文件

[英]Using Python CGI for a big HTML file

我有一個名為exercise.html的大型html文件,我需要通過Python CGI生成一個som的東西。 我想問你打印這個HTML的最佳方法是什么。

我知道有可能通過使用格式方法%s,%i等的print方法:

print '''<html>
<head><title>My first Python CGI app</title></head>
<body> 
<p>Hello, 'world'!</p>
.
.
<div>%s</div>
.
.
</body>
</html>''' % generated_text

但這個HTML真的很大,這只是一個解決方案嗎?

你應該考慮使用像Jinja2這樣的模板語言。

這是一個簡單的例子,直接來自上面的鏈接:

>>> from jinja2 import Template
>>> template = Template('Hello {{ name }}!')
>>> template.render(name='John Doe')

通常,雖然您將模板保存在文件中,然后加載/處理它們:

from jinja2 import Environment, PackageLoader
# The env object below finds templates that are lcated in the `templates`
# directory of your `yourapplication` package.
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')

如上所示,模板允許您將variables放入模板中。 將文本放在{{}}中會使其成為模板變量。 渲染模板時,使用關鍵字參數傳入變量值。 例如,下面的模板有一個我們通過template.render傳遞的名稱變量

這是我的名字}}。

template.render(name='Jaime')

還要考慮Python BottleSimpleTemplate Engine )。 值得注意的是,bottle.py支持mako,jinja2和cheetah模板。

%表示python代碼,{{var}}是替換變量

HTML:

<ul>
  % for item in basket:
  <li>{{item}}</li>
  % end
</ul>

蟒蛇:

with open('index.html', 'r') as htmlFile:
    return bottle.template(htmlFile.read(), basket=['item1', 'item2'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM