Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

light weight template engine for python

Which is the simplest and light weight html templating engine in Python which I can use to generate customized email newsletters.

like image 765
Thejesh GN Avatar asked Dec 10 '10 05:12

Thejesh GN


People also ask

Is a template engine for Python?

Jinja, also known and referred to as "Jinja2", is a popular Python template engine written as a self-contained open source project. Some template engines, such as Django templates are provided as part of a larger web framework, which can make them difficult to reuse in projects outside their coupled library.

What template engine does Django use?

Django has a built-in templating system called Django template language(DTL). One other popular templating engine that works flawlessly with Django is Jinja2. Irrespective of the templating backend, Django has pre-defined APIs for loading and rendering different templates.

Are there Python templates?

The Python string Template is created by passing the template string to its constructor. It supports $-based substitutions. This class has 2 key methods: substitute(mapping, **kwds): This method performs substitutions using a dictionary with a process similar to key-based mapping objects.


2 Answers

Anything wrong with string.Template? This is in the standard Python distribution and covered by PEP 292:

from string import Template

form=Template('''Dear $john,

I am sorry to imform you, $john, but you will not be my husband
when you return from the $theater war. So sorry about that. Your
$action has caused me to reconsider.

Yours [NOT!!] forever,

Becky

''')

first={'john':'Joe','theater':'Afgan','action':'love'}
second={'john':'Robert','theater':'Iraq','action':'kiss'}
third={'john':'Jose','theater':'Korean','action':'discussion'}

print form.substitute(first)
print form.substitute(second)
print form.substitute(third)
like image 39
the wolf Avatar answered Oct 09 '22 05:10

the wolf


For a really minor templating task, Python itself isn't that bad. Example:

def dynamic_text(name, food):
    return """
    Dear %(name)s,
    We're glad to hear that you like %(food)s and we'll be sending you some more soon.
    """ % {'name':name, 'food':food}

In this sense, you can use string formatting in Python for simple templating. That's about as lightweight as it gets.

If you want to go a bit deeper, Jinja2 is the most "designer friendly" (read: simple) templating engine in the opinion of many.

You can also look into Mako and Genshi. Ultimately, the choice is yours (what has the features you'd like and integrates nicely with your system).

like image 105
Rafe Kettler Avatar answered Oct 09 '22 05:10

Rafe Kettler