后端模板

概述

add_mapping设置的view参数,可通过Context对象的view成员获取。利用这个特性,就可以实现各种后端模板的功能,并做到逻辑与展示的分离。

示例:dome模板

依赖: https://pypi.org/project/dome/

view.py

import dome as D
def homepage(data):
    return D.Html(
        D.Head(D.Title('home')),
        D.Body(
            "Hello, ", data['who']
        ),
    )

index.py

from lessweb import Application, Context
from view import homepage

def show_view(ctx:Context):
    data = ctx()
    return ctx.view(data).dumps()

def home(who):
    return {'who': who}

app = Application()
app.add_get_interceptor('.*', dealer=show_view)
app.add_get_mapping('/', dealer=home, view=homepage)
app.run()

请求:curl "http://localhost:8080/?who=John"
返回:

<!DOCTYPE html>
<html><head><title>home</title></head><body>Hello, John</body></html>

示例:jinja2模板

依赖: https://pypi.org/project/Jinja2/

view.tpl

<!DOCTYPE html>
<html>
  <head><title>home</title></head>
  <body>Hello, {{who}}!</body>
</html>

index.py

from lessweb import Application, Context
from jinja2 import Template

def home(who):
    return {'who': who}

def show_view(ctx:Context):
    data = ctx()
    return Template(open(ctx.view).read()).render(**data)

app = Application()
app.add_get_interceptor('.*', dealer=show_view)
app.add_get_mapping('/', dealer=home, view='view.tpl')
app.run()

请求:curl "http://localhost:8080/?who=John"
返回:

<!DOCTYPE html>
<html>
  <head><title>home</title></head>
  <body>Hello, John!</body>
</html>