[Python][Flask] templates, static files and blueprints
templates, static files and blueprints
Templates and Static Files in Flask
In a Flask project, HTML files (templates) and static files (CSS, JavaScript, images) are separated to keep the code organized.
-
Templates (HTML) belong in the configured
template_folder. Flask dynamically renders them (often with Jinja2) in response to requests. -
Static files (CSS, JS, images) belong in the configured
static_folder. Flask serves them as-is without further processing.
When customizing the folder structure, make sure that:
-
template_folderpoints to the path where the HTML templates actually reside. -
static_folderpoints to the directory containing the CSS/JS/images. -
Note: Avoid leading slashes (
/) in these arguments if a relative path is required(e.g.,template_folder='client/templates'instead of'/client/templates').
With this setup, calling render_template('index.html') finds client/templates/index.html, while references to static files in templates (e.g. url_for('static', filename='css/style.css')) correctly resolve client/static/css/style.css.
Blueprint URL Prefixes
Blueprints provide a modular way to structure the Flask routes. When registering a blueprint with an application, a url_prefix can be specified. This prefix is automatically prepended to every route in that blueprint. For instance:
blog_bp = Blueprint('blog_bp', __name__)
@blog_bp.route('/')def home(): return render_template('index.html')
app.register_blueprint(blog_bp, url_prefix='/blog')
-
The blueprint itself has a route defined at
@blog_bp.route('/'). -
Registering it with
url_prefix='/blog'means the final URL forhomebecomes/blog/. -
If a route is
@blog_bp.route('/register'), the final path is/blog/register.
In other words, url_prefix + blueprint route composes the final URL. If a route needs to require an extra segment (e.g., /blog/blog), verify that the route name is not duplicated in both the blueprint route and the prefix.
Comments
Post a Comment