template.py: rewrite _exp_piece() as simpler, non-recursive code

Expanding a single template name used to involve a relatively complex
recursive function. It made my head hurt (and it also showed up in
profiles, although not that much). The new rewrite is non-recursive,
smaller, and hopefully better commented. The whole thing is a tiny
bit faster as well, partly because I optimized some bits.
template.py: add a comment that I missed on the first go around