

Poor man's python templating - what should I worry about? - johnrob

After churning through the various templating package, I now just use triple quoted strings and dictionary substitution.  I never have to read docs, and never forget how to use it.  Also, I never run into cases that break the system.<p>myhtml = '''<p>&#60;html&#62;&#60;body&#62;<p>&#60;p&#62;%(firstname)s&#60;/p&#62;<p>&#60;p&#62;%(lastname)s&#60;/p&#62;<p>&#60;/body&#62;&#60;/html&#62;<p>''' % {'firstname':'john','lastname':'doe'}<p>It's not pretty, but I feel less hindered by this approach.  I'm curious what people think the main downsides of this are...
======
connellybarnes
The string interpolation operator isn't ideal. It isn't associative, so you
can't paste in a few variables, and then a few more later, and it raises an
exception rather than simply putting a message such as "Missing variable: X"
in the output HTML.

I fixed this by simply using string replace(), and suitably unique replace
tokens.

(Then again, I program in Notepad, preferring it for aesthetic reasons over
Emacs, so go figure :-)

~~~
bayareaguy
If missing variables are an issue you could use defaultdict.

<http://docs.python.org/lib/defaultdict-objects.html>

~~~
connellybarnes
Good point, and thanks for pointing out defaultdict(); I wasn't even aware of
that class. I suppose one could use defaultdict() to gain associativity also
(pass 'not found' variables through unmodified). I think I still slightly
prefer replace(), for uninteresting reasons.

