Flask-FlatPages

0.9.0 · active · verified Sun Apr 12

Flask-FlatPages provides an easy way to integrate flat static pages, written in formats like Markdown or reStructuredText, into a Flask web application. It is currently at version 0.9.0, primarily focusing on maintenance releases and preparing for future feature additions in an eventual 1.0 release.

Warnings

Install

Imports

Quickstart

This quickstart initializes a Flask application with Flask-FlatPages, serving flat markdown pages. It demonstrates how to configure the extension, list all available pages, and retrieve a specific page based on its path. It also includes boilerplate to create dummy files, allowing the example to run out-of-the-box.

import os
from flask import Flask, render_template
from flask_flatpages import FlatPages

# Configuration
DEBUG = True
FLATPAGES_AUTO_RELOAD = DEBUG
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'pages'
FLATPAGES_ENCODING = 'utf-8'

app = Flask(__name__)
app.config.from_object(__name__)
flatpages = FlatPages(app)

# Routes
@app.route('/')
def index():
    # All pages are available via flatpages iterable
    return render_template('index.html', pages=flatpages)

@app.route('/<path:path>/')
def page(path):
    # Get a specific page, or 404
    page = flatpages.get_or_404(path)
    return render_template('page.html', page=page)

if __name__ == '__main__':
    # Create dummy content and templates for runnable quickstart
    if not os.path.exists(FLATPAGES_ROOT):
        os.makedirs(FLATPAGES_ROOT)
    with open(os.path.join(FLATPAGES_ROOT, 'about.md'), 'w') as f:
        f.write('---\ntitle: About Us\ndate: 2024-05-15\n---\n\n# Welcome to our About Page\n\nThis is an example flat page managed by Flask-FlatPages.')
    
    if not os.path.exists('templates'):
        os.makedirs('templates')
    with open('templates/index.html', 'w') as f:
        f.write('<!doctype html>\n<html>\n<head><title>FlatPages Index</title></head>\n<body>\n    <h1>FlatPages Example</h1>\n    <ul>\n        {% for page in pages %}\n            <li><a href="{{ url_for("page", path=page.path) }}">{{ page.meta.get("title", page.path) }}</a></li>\n        {% endfor %}\n    </ul>\n</body>\n</html>')
    with open('templates/page.html', 'w') as f:
        f.write('<!doctype html>\n<html>\n<head><title>{{ page.meta.get("title", "Page") }}</title></head>\n<body>\n    <h1>{{ page.meta.get("title", "") }}</h1>\n    {{ page.html|safe }}\n</body>\n</html>')

    # Run the Flask app
    app.run(port=5000, debug=DEBUG)

view raw JSON →