[lxml-dev] Templating

Stefan Behnel stefan_ml at behnel.de
Fri Feb 6 21:32:39 CET 2009


Hi,

Audun Wilhelmsen wrote:
> I'd like to use lxml for creating a simple HTML templating engine,
> by implementing some custom tags and attributes.

Note that there are already a lot of template engines, including some that
work with lxml, such as webstring.


> A simple example:
> <p gc:text="foobar"></p>
> Would replace the text content of the tag with the variable foobar.
> 
> But I'm not sure how to implement it using lxml. I've been using  
> Genshi succesfully,  by simply processing the tag stream before  
> serializing. But I'd like to have the DOM-like capabilities and speed  
> of lxml.
> 
> What would be the best approach? I've been trying to use XPath to find  
> all the elements and attributes with a gc: prefix, but with little  
> success so far (maybe mixing namespaces with non-xml html doesn't work  
> that well?).

The HTML is (obviously) not namespace aware. But have you considered
storing your templates as XHTML? That would allow you to use namespaces at
will, without preventing you from serialising them to HTML. Also, if your
templates are XML compatible (even without an XHTML namespace), you can
just parse them with the XML parser instead of the HTML parser.

Stefan


More information about the lxml-dev mailing list