How to use genshi.builder to programmatically build an HTML document?

I recently discovered the genshi.builder module. It reminds me of the Divmod Nevow Stan module. How to use genshi.builder.tag to create an HTML document with a specific doctype type? Or is this even a good thing? If not, what is the right way?

+3
source share
2 answers

It is impossible to build a whole page using only genshi.builder.tag- you will need to perform some operation on the resulting stream to insert a doctype. Also, the resulting code would look awful. The recommended way to use Genshi is to use a separate template file, generate a stream from it, and then convert this stream to the desired type of output.

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

- , , . .

+4

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__
+2

Source: https://habr.com/ru/post/1697302/


All Articles