First Encounter with Genshi
Wednesday, 4 June 2008
I was playing around with code generation of some scaffolding-style code for CodeIgniter. Initially, python’s string interpolation operator % sufficed. As time progressed, it became clearer that resorting to a templating library buys me cleaner code.
Problem #1
The $ used by Genshi for string interpolation conflicts with PHP’s $variables.
Solution #1
After 10 minutes of source diving (by the way, Genshi source is a work of art - wish I could write like that).
import genshi.template.interpolation
genshi.template.interpolation.PREFIX = '^'
from genshi.template import TextTemplate
template = TextTemplate("$this->^{foo} = 'home';")
stream = template.generate(foo="customer")
print stream
Problem #2
The generated output quotes the > into >
Solution #2
The Stream render() method takes a parameter specifying the kind of escaping.
print stream.render('text')
Overall Solution
from genshi.template import TextTemplate
import genshi.template.interpolation
genshi.template.interpolation.PREFIX = '^'
for tablename, table in specs.items():
fd = open('controllers/%s.php' % tablename, 'w')
template = TextTemplate(open('controllers.php', 'r'), filename='controller.php')
print template.generate(tablename=tablename, columns=table).render('text')