仅使用无法构建整个页面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')
Run Code Online (Sandbox Code Playgroud)
生成的页面中将没有空格——它看起来很正常,但是您将很难阅读源代码,因为它完全在一行上。实现适当的过滤器以添加空格作为练习留给读者。
| 归档时间: |
|
| 查看次数: |
1544 次 |
| 最近记录: |