Including these three, Python has accumulated many template languages.

When you need to write Python Web applications using the template language, there are many robust solutions.

There are Jinja2, Genshi and Mako. There are even solutions like Chameleon, which are somewhat dated but still recommended by Pyramid.

Python has been around for a long time. At this point, deep in the system, it has accumulated a few mostly forgotten template languages that are worth a try.

Like a cute koala in a eucalyptus tree, living happily and sometimes dangerously in its own ecosphere, these are template languages that few people have ever heard of, and even fewer have ever used.

3, string. The Template

Have you ever wondered, “How do you get a template language that doesn’t have any features and doesn’t require PIP Install to install anything?” The Python standard library already provides you with the answer. The String. Template class is a minimal templating language, although there are no loops or conditions.

It’s simple to use.

>>> import string
>>> greeting = string.Template("Hello, $name, good $time!")
>>> greeting.substitute(name="OpenSource.com", time="afternoon")
'Hello, OpenSource.com, good afternoon! '
Copy the code

2, the twisted. Web. The template

What do you give an all-inclusive library?

Not a template language, of course, because it already exists. There are two template languages nested in twisted. Web. template. One is XML-based and has a nice document.

But it has another, one based on using Python as a Domain-specific language (DSL) to generate HTML documents.

It is based on two primitives: contain the twisted label objects. Web. The template. The tags and render their twisted. Web. Template. FlattenString. Because it is part of Twisted, it has built-in support for efficient asynchronous rendering.

This example will render a small page:

async def render(reactor):
    my_title = "A Fun page"
    things = ["one"."two"."red"."blue"]
    template = tags.html(
            tags.head(
                tags.title(my_title),
            ),
            tags.body(
                tags.h1(my_title),
                tags.ul(
                    [tags.li(thing) for thing in things],
                ),
                tags.p(
                    task.deferLater(reactor, 3, lambda: "Hello "),
                    task.deferLater(reactor, 3, lambda: "world!"),
                )
            )
    )
    res = await flattenString(None, template)
    res = res.decode('utf-8')
    with open("hello.html".'w') as fpout:
        fpout.write(res)
Copy the code

This template is regular Python code that uses tags.

to indicate a hierarchy. Render strings are supported natively, so any string is fine.

To render it, all you need to do is add the call:

from twisted.internet import task, defer
from twisted.web.template import tags, flattenString

def main(reactor):
    return defer.ensureDeferred(render(reactor))
Copy the code

Finally write:

task.react(main)
Copy the code

In 3 seconds (instead of 6), it will render a nice HTML page. In practice, these deferLater versions could be calls to HTTP apis: they would be sent and processed in parallel without any effort. I recommend you read about better use of Twisted. However, this is already working.

1, Quixote

“But Python is not a domain-specific language optimized for the HTML domain,” you say. What if there was a language that could be converted to Python, but was better suited to defining templates rather than solving them as-is like Python? Use the “Python Template Language” (PTL) if you can.

Writing your own language is sometimes described as a Don Quixote project that attacks imaginary enemies. Quixote, the creator of Quixote (found in PyPI), was unfazed when he decided to do just that.

The same template of Twisted as above will be rendered below. Warning: The following is not valid Python code:

import time

def render [html] ():
    my_title = "A Fun page"
    things = ["one"."two"."red"."blue"]
    "<html><head><title>"
    my_title
    "</head></title><body><h1>"
    my_title
    "</h1>"
    "<ul>"
    for thing in things:
        "<li>"
        thing
        "</li>"
    "<p>"
    time.sleep(3)
    (lambda: "Hello ")()
    time.sleep(3)
    (lambda: "world!") ()"</p>"
    "</body></html>"

def write():
    result = render()
    with open("hello.html".'w') as fpout:
        fpout.write(str(result))
Copy the code

However, if you put it in the template. PTL file, you can import it into Quixote and write a version that can render the template:

>>> from quixote import enable_ptl
>>> enable_ptl()
>>> import template
>>> template.write()
Copy the code

Quixote installs an import hook that converts PTL files to Python. Note that this rendering takes 6 seconds, not 3 seconds. You no longer get free asynchrony.

There are too many templates in Python

Python libraries have a long and convoluted history, and some of them can achieve more or less similar results (for example, Python package management).

I hope you enjoy exploring these three ways you can create templates in Python. Also, I recommend starting with one of these three libraries.

Do you have another esoteric approach to templating? Please share in the comments below!


Via: opensource.com/article/20/…

By Moshe Zadka, Lujun9972

This article is originally compiled by LCTT and released in Linux China