python - Create Flask views that render different templates without repeating code -


i want define multiple endpoints render different templates, without writing out each one. endpoints similar, 1 looks like:

    @app.route('/dashboard/')     def dashboard():         return render_template('endpoints/dashboard.html') 

i tried defining function in loop each endpoint name, problem name of function stays same , flask raises error that.

routes = ['dashboard', 'messages', 'profile', 'misc']  route in routes:     @app.route('/' + route + '/')     def route():         return render_template('endpoints/' + route + '.html') 

how can create these views without repeating myself?

you don't want this. instead, use variable in route capture template name, try render template, , return 404 error if template doesn't exist.

from flask import render_template, abort jinja2 import templatenotfound  @app.route('/<page>/') def render_page(page):     try:         return render_template('endpoints/{}.html'.format(page))     except templatenotfound:         abort(404) 

alternatively, , less preferably, can use same function name long provide flask unique endpoint names. default name name of function, why flask complains.

for name in routes:     @app.route('/', endpoint=name)     def page():         return render_template('endpoints/{}.html'.format(name)) 

Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -