Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python template engine

Could it be possible if somebody could help me get started in writing a python template engine? I'm new to python and as I learn the language I've managed to write a little MVC framework running in its own light-weight-WSGI-like server.

I've managed to write a script that finds and replaces keys for values: (Obviously this is not how my script is structured or implemented. this is just an example)

from string import Template

html  = '<html>\n'
html += '  <head>\n'
html += '  <title>This is so Cool : In Controller HTML</title>\n'
html += '  </head>\n'
html += '  <body>\n'
html += '    Home | <a href="/hi">Hi ${name}</a>\n'
html += '  </body>\n'
html += '<html>'

Template(html).safe_substitute(dict(name = 'Arturo'))

My next goal is to implement custom statements, modifiers, functions, etc (like 'for' loop) but i don't really know if i should use another module that i don't know about. I thought of regular expressions but i kind feel like that wouldn't be an efficient way of doing it

Any help is appreciated, and i'm sure this will be of use to other people too.

Thank you

like image 487
jturo Avatar asked Jun 02 '10 07:06

jturo


2 Answers

There are many powerful template languages supported by Python out there. I prefer Jinja2. Also take a look at Mako and Genshi.

Mako is fastest among three, but it's ideology allows to have a complex code logic right in template that provoke MVC principles violation from time to time.

Genshi has excellent conception, especially powerful feature is inversed template inheritance. But it is slowest among three and as practice shows all its features are often overkill in real project.

Jinja2 is a golden middle in my personal opinion. It is easily extensible, quite fast and familiar to many since it use syntax similar to Django templates and Liquid template language.

like image 192
nkrkv Avatar answered Sep 28 '22 19:09

nkrkv


well, as you said you are a python rookie, and the ONLY reason you are writting a new MVC framework and template engine from scratch, is for learning purposes, you should not care about performance IMHO.

But if you decide to put something in production, you should consider using already existent template engines, such as jinja2, mako, genshi and so on.

Anyway if you want to play around, there is a nice example of lightweight web python framework at: http://github.com/breily/juno

and lightspeed template engine at http://github.com/eklitzke/spitfire

happy hacking!

like image 23
Gabriel Falcão Avatar answered Sep 28 '22 19:09

Gabriel Falcão