Micro python HTML templating engine
Idea that XML is not the most compact form of trees markup is not new. Like idea that HTML is hard to write by hand and should be dynamically generated on server. (Or compiled. There is even whole class of software – site compilers, which can be cheaper equivalents to content management systems). Furthermore, today even CSS can be compiled from SASS and JavaScript can be compiled from CoffeScript. Which means that web is making a new leap to a more high-level languages, which are compiled to “machine code” (and in our case “machine” is a browser).
Oh, and now I should return to my point. XML document is just a tree. HTML too. And code of any programming language also represent a tree. This is most explicitly seen in Lisp-like languages where we have a lot of parentheses. So why not to write web-pages in Lisp? Or, as I don’t know Lisp good enought, in Python?
Now I am presenting you my brand new lispy micro html templating engine. It is supercompact, and probably superslow, but I am too lazy to test. Also it doesn’t have escaping support, so use with caution.
#!/usr/bin/python3 #coding=utf8 def generic_tag(name, *inner_html, **attrs): tag_attrs = '' if attrs: tag_attrs = ' ' + ' '.join(( '%s="%s"' % (k, v) for k, v in attrs.items() )) if inner_html: return '<%(name)s%(attrs)s>%(html)s</%(name)s>' % { 'name': name, 'html': ''.join(inner_html), 'attrs': tag_attrs, } else: return '<%(name)s%(attrs)s />' % { 'name': name, 'attrs': tag_attrs, } class Html(): def __getattr__(self, name): def func(*inner_html, **attrs): return generic_tag(name, *inner_html, **attrs) return func h = Html() def document(title, *body_elements): return h.html( h.head( h.title(title) ), h.body( h.h1(title), *body_elements ) ) print(document('Lispy python templates', h.img(src='http://example.com/image.jpg', width='100', alt='title'), h.div('Привіт світе! ', style="color:green"), h.br(), h.p('Це мій новий шаблонізатор. <important>Без HTML екскейпингу :(</important>'), *[h.p('Параграф %s') % i for i in range(10)] ))
Pardon my poor grammar and spelling, but I write as can. If you spot some mistakes here – don’t be ashamed to point at them, I will be glad to learn. Special thanks to J.Tim.
great piece of code!
danbstt
22 Грудня, 2011 at 01:40
Thanks man.
bunyk
22 Грудня, 2011 at 21:19
От так завжди. Придумаєш щось нове – а виявляється що воно вже багато років як не нове, просто ти не знав як його знайти: http://stackoverflow.com/a/56269/911555
bunyk
28 Березня, 2012 at 14:01