So I am just a little confused on how to build pages with flask without having to state each view.
How would I make a blue print that would pickup on the pages i want to load?
say these are my example pages
templates/
layout.html
section1/
subsection/index.html
subsection2/index.html
section2
subsection/index.html
childofsubsection/index.html
I would liked to assume if i went to example.com/section1/subsection/ it would know to look for its corresponding page without having to specifically stating it. The documentation http://flask.pocoo.org/docs/blueprints/ gets very close to explaining this, but i am still a little lost.
from flask import Flask
from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
also, not sure where this was supposed to go? this looks like it would go in the application.py, but asks to import from "yourapplication"
Very new to flask and not a python expert either. Really just need some dumbing down :)
If you'd like to see an example of Blueprint
usage, you can have a look at this answer.
About the "template auto-find" part of your question: like the documentation explains, blueprints allows to specify a folder where static files and/or templates will be looked for, this way you don't have to specify the full path to the template file in your render_template()
call, but only the file name.
If you wanted your views to "magically" know which file they should pick, you have to do a bit of hack. A solution, for example, could be to apply a decorator on your view that would make it pick the template file based on the function name, such a decorator would look like this:
from functools import wraps
from flask import render_template
def autorender(func):
@wraps(func)
def wrapper(*args, **kwargs):
context = func(*args, **kwargs)
return render_template('%s.html' % func.func_name, **context)
return wrapper
Then you would just have to return the context in your view as a dict (or an empty dict if there is no context):
@my_blueprint.route('/')
@autorender
def index():
return {'name': 'John'} # or whatever your context is
And it would automatically pick the template named index.html
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With