Genshi transforms with callbacks (example)

5 June 2008
19:55

By cmlenz as Python

1 from genshi.filters import Transformer
2 from genshi.input import HTML
3
4 def counter(offset=0, step=1):
5 pos = [offset - step]
6 def _generate():
7 pos[0] += step
8 yield "%02d. " % pos[0]
9 return _generate
10
11 html = HTML("""<ul>
12 <li>One</li>
13 <li>Two</li>
14 <li>Three</li>
15 </ul>""")
16 print html | Transformer('.//li').prepend(counter())
17
18 # <ul>
19 # <li>00. One</li>
20 # <li>01. Two</li>
21 # <li>02. Three</li>
22 # </ul>

Download Raw Source

Comments

  1. athomas says:

    6 June 2008
    04:40

    Yep, using a generator is the best method I've come up with for inserting content "with state". I'm not sure how this could be formalised, or even if it's worth the effort.