[Answer]-Custom templates in python

1👍

If all you want is to just do simple string formatting, python includes the str.format() method as well as Template Strings.

Straight from the docs

>>> from string import Template
>>> s = Template('$who likes $what')
>>> s.substitute(who='tim', what='kung pao')
'tim likes kung pao'
>>> d = dict(who='tim')
>>> Template('Give $who $100').substitute(d)
Traceback (most recent call last):
...
ValueError: Invalid placeholder in string: line 1, col 11
>>> Template('$who likes $what').substitute(d)
Traceback (most recent call last):
...
KeyError: 'what'
>>> Template('$who likes $what').safe_substitute(d)
'tim likes $what'

If you need to introduce any sort of logic into the templates, then I would be so bold as to say it will be way over your head to write yourself properly and you’ll want to use a library. Jinja2 is an excellent template library for general purpose use. If you’ve ever used Django’s templating system, it will be a breeze to use as Jinja2 is based on Django.

Some code I’ve used with Jinja2

import jinja2

jinja2.env = jinja2.Environment(
    loader=jinja2.PackageLoader(package_name=__name__,
                                package_path='templates'),
    trim_blocks=True,
    extensions=[
        'jinja2.ext.with_',  # add the with tag
    ],
)

context = {
    'results': results,
    'javascript': js,
    'css': css,
    'version': '.'.join(str(n) for n in __version__),
}

template = env.get_template('my_template.html')

rendered_template = template.render(context)

In my_template.html

<html>
  <head>
    <title>Hello World</title>
    <style>{{ css }}</style>
    <script>{{ javascript }}</script>
  </head>
  <body>
    <h1>Hello world</h1>
    <ul>
      {% for result in results %}
        <div>
           {{ result.winner_name }}<br />
           {{ result.get_score() }}
        </div>
      {% endfor %}
    </ul>
  </body>
</html>

One difference between Django templating and Jinja2 templating is that Jinja2’s philosophy wasn’t about making it easy for designers to use; so, function calls are allowed within templates.

Leave a comment