后端模板

概述

dealer可以直接返回页面内容的字符串

示例:mako模板

安装mako: pypi文档

view.tpl

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

index.py

from mako.template import Template  # type: ignore
from lessweb import Application, Context, interceptor

def page_view(tpl):
    def processor(ctx: Context):
        ret = ctx()
        if ctx.request.is_json():
            return ret
        else:
            return Template(filename=tpl, input_encoding='utf-8', output_encoding='utf-8').render(**ret)
    return processor

@interceptor(page_view('view.tpl'))
def home(who: str):
    return {'who': who}

app = Application()
app.add_get_mapping('/', dealer=home)
app.run()

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

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

请求2:curl -H 'Content-Type: application/json' "http://localhost:8080/?who=John"
返回:

{"who": "John"}