Edgewall Software

Version 1 (modified by cmlenz, 12 years ago) (diff)

Initial version

Generating Markup Programmatically

Markup provides a builder module which lets you generate markup from Python code using a very simple syntax.

The main entry point to the builder module is the tag object (which actually is an instance of the ElementFactory class). Elements can be created through this tag object using attribute access, for example:

>>> from markup.builder import tag
>>> doc = tag.p('Some text and ', tag.a('a link', href='http://example.org/'), '.')
>>> doc
<Element "p">

This produces an Element instance which can be further modified to add child nodes and attributes. It can also be directly rendered to XML text:

>>> print doc
<p>Some text and <a href="http://example.org/">a link</a>.</p>

This is basically a shortcut for converting the Element to a stream and rendering the stream:

>>> stream = doc.generate()
>>> stream
<markup.core.Stream object at 0x72d230>
>>> print stream
<p>Some text and <a href="http://example.org/">a link</a>.</p>

The full functionality of streams is available for streams generated this way. For example, sub-streams can be extracted using XPath expressions with the select() method:

>>> substream = stream.select('a')
>>> substream
<markup.core.Stream object at 0x71e090>
>>> print substream
<a href="http://example.org/">a link</a>