简体   繁体   中英

Render Multiple Jinja Templates with One Handler

Hello Stackoverflow Guru's!

I'm a complete newb, and I've got a question that I can't seem to find the answer to (hopefully because it's so simple nobody has bothered to ask).

I'm designing a website that has a bunch of recipes using google app engine. I'd like to be able to render a bunch of the recipe pages using one handler, because I plan of having lots of recipes later and I don't want to have to make a new handler for each one. My code is below:

import urllib2
import webapp2
import jinja2
import os


JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)

class Handler(webapp2.RequestHandler):
def write(self, *a, **kw):
    self.response.out.write(*a, **kw)

def render_str(self,template,**params):
    t = JINJA_ENVIRONMENT.get_template(template)
    return t.render(params)

def render(self,template,**kw):
    self.write(self.render_str(template,**kw))

class MainHandler(Handler):
def get(self):
    template = JINJA_ENVIRONMENT.get_template('main.html')
    self.response.write(template.render())

class RecipeHandler(Handler, recipe):
def get(self, recipe):
    recipe_pages = {
    'carbonara' : 'carbonara.html'
    'burger' : 'burger.html'
    }
    if recipe in recipe_pages:
        template = JINJA_ENVIRONMENT.get_template(recipe_pages[recipe])
        self.response.write(template.render())
    else:
        self.abort(404)



app = webapp2.WSGIApplication([
('/', MainHandler),
('/carbonara', RecipeHandler(carbonara)),
('/burger',RecipeHandler(burger)),
], debug=True)

I basically want to avoid writing out a "CarbonaraHander" and "BurgerHandler", and just use "RecipeHandler" to render both pages. I know this should be possible, but I have no idea how to do it.

Any help is appreciated!

Edit: I think I should be using something called regular expressions? But I don't really understand how they need to be used in this case.

AFAIK you can't pass args to the handler, you need to extract them from the request. This is what I'd do (pushed it a bit further to directly use the template name in the URl routing):

class RecipeHandler(Handler):

    def extract_template_name_from_request(self):

        return self.request.path_info[9:] # strip leading '/recipes/' (or whatever else you need)

    def get(self):

        template_name = self.extract_template_name_from_request()
        try:
            template = JINJA_ENVIRONMENT.get_template(template_name)
        except Exception:
            # can't locate a template matching the requested path
            self.abort(404)
            return

        # prepare the template values as needed
        values = {'recipe': {'name': template_name[:-5]}}  # just an example

        try:
            self.response.write(template.render(values))
        except Exception:
            # failure rendering the template
            self.abort(500)

app = webapp2.WSGIApplication([
    ('/recipes/.*.html', RecipeHandler), # see extract_template_name_from_request()
    ('/.*', MainHandler),
], debug=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM