简体   繁体   中英

Custom templates in python

I am trying to implement custom template formatting in python accomplishing two things

  1. Django like delimiter

    {{ placeholder }}

eg.

from string import Template

class MyTemplate(Template):
     delimiter="{{..}}" #it is only for clarification purpose, though it is invalid

mt = MyTemplate("HELLO {{ world }}")
mt.substitute(world="WORLD")
  1. If there is key error or value error, skip that identifier.

    class MyTemplate(Template): delimiter="{{..}}" #it is only for clarification purpose

    data = "HELLO {{ world }}, this is 1st program {{ program }}"

    mt = MyTemplate(data)

    mt.substitute(world="WORLD")

then o/p should be,

 HELLO WORLD, this is 1st program

As per my knowledge, we can use templates engines like jinja2 but that is my last option. I am preferring to do it using python native libraries.

Though if you want to suggest any template engine (if possible with example), then it will be also good.

Thanks in advance.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM