Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template in python

How to write a function render_user which takes one of the tuples returned by userlist and a string template and returns the data substituted into the template, eg:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> render_user(('[email protected]', 'matt rez', ), tpl)
"<a href='mailto:[email protected]>Matt rez</a>"

Any help would be appreciated

like image 843
Tara Avatar asked Mar 22 '11 00:03

Tara


People also ask

Why template is used in Python?

Python Templates are used to substitute data into strings. With Templates, we gain a heavily customizable interface for string substitution (or string interpolation).

What is Template render in Python?

render_template is a Flask function from the flask. templating package. render_template is used to generate output from a template file based on the Jinja2 engine that is found in the application's templates folder. Note that render_template is typically imported directly from the flask package instead of from flask.

Does Python have template class?

In python, template is a class of String module. It allows for data to change without having to edit the application. It can be modified with subclasses. Templates provide simpler string substitutions as described in PEP 292.

What are template engines in Python?

Template engines take in tokenized strings and produce rendered strings with values in place of the tokens as output. Templates are typically used as an intermediate format written by developers to programmatically produce one or more desired output formats, commonly HTML, XML or PDF.


1 Answers

No urgent need to create a function, if you don't require one:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> s = tpl % ('[email protected]', 'matt rez', )

>>> print s
"<a href='mailto:[email protected]'>matt rez</a>"

If you're on 2.6+ you can alternatively use the new format function along with its mini language:

>>> tpl = "<a href='mailto:{0}'>{1}</a>"
>>> s = tpl.format('[email protected]', 'matt rez')

>>> print s
"<a href='mailto:[email protected]'>matt rez</a>"

Wrapped in a function:

def render_user(userinfo, template="<a href='mailto:{0}'>{1}</a>"):
    """ Renders a HTML link for a given ``userinfo`` tuple;
        tuple contains (email, name) """
    return template.format(userinfo)

# Usage:

userinfo = ('[email protected]', 'matt rez')

print render_user(userinfo)
# same output as above

Extra credit:

Instead of using a normal tuple object try use the more robust and human friendly namedtuple provided by the collections module. It has the same performance characteristics (and memory consumption) as a regular tuple. An short intro into named tuples can be found in this PyCon 2011 Video (fast forward to ~12m): http://blip.tv/file/4883247

like image 87
miku Avatar answered Oct 14 '22 18:10

miku