【问题标题】:How to render template directly without having a handler如何在没有处理程序的情况下直接呈现模板
【发布时间】:2013-08-30 14:56:15
【问题描述】:

我的 GAE 项目的设置如下:

/static/.* --> images, css, js
/rest/.* --> a script handling all rest resources using webapp2 handlers

我想使用 jinja2 模板基本上创建一些 html 页面,但例如使用 jinja2 提供的模板继承。或多或少要做服务器端包括。

所以所有其他传入的请求都应该直接渲染一个模板,例如:

/ --> index template
/index.html --> index template
/some/path/to/a/page.html --> /some/path/to/a/page template
/some/path/to/a/page --> /some/path/to/a/page template

我想同时匹配 .html 和不带扩展名的路径。

我不想为我的所有路径创建路由,只是一些可以处理这个问题的智能脚本。这可能吗?

【问题讨论】:

    标签: python google-app-engine python-2.7 jinja2 webapp2


    【解决方案1】:

    是的,你可以。但仍然需要单个处理程序:

    # app.yaml
    - url: /rest/.*
      script: main.app
    
    # main.py
    class PageHandler(webapp2.RequestHandler):
        def get(self, page):
            if not page.endswith('.html'):
                page += '.html'
            self.response.write(self.jinja2.render_template(page))
    
    app = webapp2.WSGIApplication([
        webapp2.RedirectRoute('/rest/<page>', PageHandler, name='page'),
    ], debug=True)
    

    然后你只需将你的页面链接到 /rest/index.html 或 /rest/path/to/page

    但是,如果您纯粹将它用于静态文件,它仍将使用实例来生成这些页面,如果您愿意,可以使用我的 app-engine-static github 项目。它基本上是一个项目,可以帮助您使用 jinja2 构建动态站点,然后生成静态文件,这将与应用引擎的内置 cdn 一起使用,并且不会消耗实例时间: http://blog.altlimit.com/2013/08/host-static-website-on-google-app.html

    【讨论】:

    • 感谢分享这个,我也会看看你的 app-engine-static 项目,看看最适合我的需求。
    猜你喜欢
    • 2012-10-30
    • 2021-01-02
    • 2013-08-30
    • 1970-01-01
    • 2013-06-21
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多