2008-09-21 47 views

回答

4

這是不可能只使用genshi.builder.tag構建整個頁面 - 你需要執行對產生的流進行一些手術以插入文檔類型。此外,由此產生的代碼看起來很可怕。推薦使用Genshi的方法是使用單獨的模板文件,根據它生成流,然後將該流渲染爲所需的輸出類型。

genshi.builder.tag主要用於需要從Python內部生成簡單標記的情況,比如當您構建表單或對輸出進行某種邏輯重大修改時。

見文檔:

如果你真的想生成只使用builder.tag一個完整的文件,這個(完全未經測試)代碼可能是一個好的起點:

from itertools import chain 
from genshi.core import DOCTYPE, Stream 
from genshi.output import DocType 
from genshi.builder import tag as t 

# Build the page using `genshi.builder.tag` 
page = t.html (t.head (t.title ("Hello world!")), t.body (t.div ("Body text"))) 

# Convert the page element into a stream 
stream = page.generate() 

# Chain the page stream with a stream containing only an HTML4 doctype declaration 
stream = Stream (chain ([(DOCTYPE, DocType.get ('html4'), None)], stream)) 

# Convert the stream to text using the "html" renderer (could also be xml, xhtml, text, etc) 
text = stream.render ('html') 

生成的頁面將不會有空白 - 看起來很正常,但您將很難閱讀源代碼,因爲它完全位於同一行。實現合適的過濾器來添加空格作爲練習留給讀者。

+0

這是有道理的。聽起來像你可能用來建立一個HTML片段加載到頁面使用AJAX或東西? – 2008-09-22 02:22:11

2

Genshi.builder用於「以編程方式生成標記流」[1]。我相信它的目的是作爲模板語言的後端。您可能正在尋找用於生成整個頁面的模板語言。

可以,但是做到以下幾點:

>>> import genshi.output 
>>> genshi.output.DocType('html') 
('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd') 

見其他DOCTYPES這裏:http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType

[1] genshi.builder.__doc__ 
+0

有沒有辦法使用genshi構建html文檔?我正在尋找類似斯坦的東西。如果這不適合使用genshi,那很好,但我想知道是否是這種情況。 – 2008-09-22 01:21:42

相關問題