zoukankan      html  css  js  c++  java
  • 动手写一个简单的Web框架(模板渲染)

    动手写一个简单的Web框架(模板渲染)

    在百度上搜索jinja2,显示的大部分内容都是jinja2的渲染语法,这个不是Web框架需要做的事,最终,居然在Werkzeug的官方文档里找到模板渲染的代码。

    关于模板渲染即render_template,简单实现代码其实只有几行,下面是我的代码:

    def render_template(path, template, **kwargs):
        # 获取模板文件夹位置
        template_path = os.path.join(path, 'templates')
        # 实例化Environment
        jinja_env = Environment(loader=FileSystemLoader(template_path), autoescape=True)
        # 获取得到模板
        t = jinja_env.get_template(template)
        # 返回渲染的模板
        return Response(t.render(kwargs), mimetype='text/html')
    

    这样就好了,关于调用,和Flask有几分相似,但是由于简化,需要传入Web程序的路径参数,以定位得到templates文件夹位置,关于其实例化等等代码可参考我的上一篇博客

    import os
    def Render(request):
        name = request.args.get('name', 'World')
        return render_template(os.path.dirname(__file__), 'test1.html', name=name)
    app.add_url_rule(rule='/render', view_func=Render, methods=['GET'])
    

    运行效果:

  • 相关阅读:
    HDU1026 Ignatius and the Princess I
    luogu_1865 A % B Problem
    luogu_1092 虫食算
    luogu_1111 修复公路
    luogu_1265 公路修建
    luogu_2330 [SCOI2005]繁忙的都市
    luogu_1613 跑路
    luogu_3386 【模板】二分图匹配
    luogu_3388 【模板】割点(割顶)
    luogu_2327 扫雷
  • 原文地址:https://www.cnblogs.com/JoshuaYu/p/12973349.html
Copyright © 2011-2022 走看看