Blueprints

Blueprints are a way to organize your JsWeb application into smaller, reusable components. A blueprint defines a collection of routes that can be registered with an application, optionally with a URL prefix.

Creating a Blueprint

To create a blueprint, you instantiate the Blueprint class. You need to give it a name and an optional URL prefix.

# in a file like admin/views.py
from jsweb.blueprints import Blueprint

admin_bp = Blueprint('admin', url_prefix='/admin')

Defining Routes

Once you have a blueprint object, you can use its @route() decorator to define routes, just like you would with the main application object.

# admin/views.py (continued)
from jsweb.response import html

@admin_bp.route('/dashboard')
def dashboard(req, res):
    return html('<h1>Admin Dashboard</h1>')

@admin_bp.route('/users')
def list_users(req, res):
    # ... logic to fetch users ...
    return html('<ul><li>User 1</li><li>User 2</li></ul>')

The endpoint for a blueprint route is automatically prefixed with the blueprint's name (e.g., 'admin.dashboard'). This prevents endpoint name collisions with your main application or other blueprints.

Registering the Blueprint

To make the blueprint's routes accessible, you must register it with your main JsWebApp instance using the register_blueprint() method.

# app.py
from jsweb.app import JsWebApp
import config
from admin.views import admin_bp # Import the blueprint

app = JsWebApp(config=config)

# Register the blueprint
app.register_blueprint(admin_bp)

# The routes are now active:
# /admin/dashboard
# /admin/users