代码之家  ›  专栏  ›  技术社区  ›  Jeremy Cantrell

如何使用genshi.builder以编程方式构建HTML文档?

  •  3
  • Jeremy Cantrell  · 技术社区  · 16 年前

    我最近发现了genshi.builder模块。它让我想起了Divmod Nevow的Stan模块。如何使用genshi.builder.tag构建具有特定doctype的HTML文档?或者这是一件好事吗?如果没有,是什么 正确的 方式?

    2 回复  |  直到 16 年前
        1
  •  4
  •   John Millikin    16 年前

    不可能只使用 genshi.builder.tag --您需要对生成的流执行一些操作来插入doctype。此外,生成的代码看起来很恐怖。建议使用genshi的方法是使用单独的模板文件,从中生成流,然后将该流呈现为所需的输出类型。

    Genshi.建筑商标签 在需要从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')
    

    结果页面中不会有空白——看起来很正常,但是您很难阅读源代码,因为它完全在一行上。实现适当的过滤器来添加空白是留给读者的一个练习。

        2
  •  2
  •   alif    16 年前

    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')
    

    请参阅此处的其他文档类型: http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType

    [1] genshi.builder.__doc__
    
    推荐文章