Search code examples
pythongoogle-app-enginepython-2.7jinja2webapp2

How to render template directly without having a handler


My GAE project has a setup like:

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

I want to use jinja2 templates to basically create some html pages but e.g. using the template inheritance jinja2 provides. More or less to do server side includes.

So all other incoming requests should directly render a template, e.g:

/ --> 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

I would like to match both .html and paths without extension.

I don't want to create routes for all my paths, just some smart script that can handle this. Would this be possible?


Solution

  • Yes, you can. But still need the single handler for that:

    # 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)
    

    Then you just link your pages with /rest/index.html or /rest/path/to/page

    But if you are purely using this for static files, this will still use an instance to generate these pages, if you like you could use my app-engine-static github project. It's basically a project that would help you build dynamic sites using jinja2 then generate the static files and this will serve with app engine's built-in cdn and not consume instance hours: http://blog.altlimit.com/2013/08/host-static-website-on-google-app.html