Menus and shells

Table of contents

  1. Introduction
  2. How an entry reaches the shell
  3. Adding a menu entry
    1. Choosing who sees an entry
    2. Marking the current entry
    3. Marking another feature’s entry as current
    4. Showing a badge
    5. Adding a section
  4. Drawing the menus in a shell
  5. Hiding and reordering entries in your product
  6. Moving a shell from menu slots to the registry
  7. Choosing a page’s layout
  8. What the application shell provides
  9. Loading assets per shell
  10. Using the CSP nonce
  11. Advanced
  12. Reference
    1. register_menu_item and register_user_menu_item
    2. register_menu_section
    3. Default sections
    4. Reading the menus
    5. Errors
  13. See also

Introduction

A product renders through two shells, the signed-in application and the public website. Your feature declares its menu entries, and on each request the shell draws the ones the account may open. You never write menu markup.

from flask_babel import lazy_gettext as _l

from splent_framework.nav.menu_registry import register_menu_item


def init_feature(app):
    register_menu_item("notes", _l("Notes"), endpoint="notes.index", icon="file-text")

Every signed-in account now sees Notes in the sidebar. Remove the feature and the entry goes with it.


How an entry reaches the shell

How menu entries go from the features to the shell on each request AT STARTUP EACH REQUEST TO THE SHELL Features, in init_feature register_menu_item(...) register_user_menu_item(...) register_menu_section(...) The product's pyproject [tool.splent.layout.menu] hide and order, by key not hidden by the product the section admits the account a URL from the endpoint roles, and the endpoint's policy the current entry, then badges Plain data label, url, icon active, aria_current badge, section, external from menu_sections() and user_menu(), which the theme turns into markup shell('app') names the layout a page extends, and a product may point it at another file. get_assets(kind, shell='app') gives each shell its own assets. csp_nonce() gives each request its own nonce, for the tags a template owns.
Features declare entries once. On every request the registry keeps what the account may open, marks the current entry and hands plain data to the shell, which owns all of the markup.

The registry hands the shell plain data, so the shell owns all of the markup. A shell that never calls menu_sections() shows none of the entries.


from flask_babel import lazy_gettext as _l

from splent_framework.nav.menu_registry import register_menu_item, register_user_menu_item


def waiting_review():
    return Note.query.filter_by(reviewed=False).count()


def init_feature(app):
    register_menu_item(
        "notes_review", _l("Review"), endpoint="notes.admin_review",
        icon="check-circle", section="admin", badge=waiting_review,
    )
    register_user_menu_item("user_notes", _l("My notes"), endpoint="notes.mine", icon="user")

register_menu_item adds an entry to the sidebar, and register_user_menu_item to the account’s dropdown. Register them from init_feature, never in a module’s body, because the menus are emptied before the features load.

Write the label with lazy_gettext, so it follows the language switcher and feature:translate --extract finds it. Give an endpoint, or an href for an address outside the app. An endpoint this product does not have, or one that needs URL arguments, leaves the entry out.

The key is how products hide and order the entry, so treat it as public. Use lowercase words joined by underscores, and start a user menu key with user_, as in user_notes next to the sidebar’s notes.

Choosing who sees an entry

Most entries need no roles. An entry takes the roles of the screen it opens, so the menu never offers a door that answers 403.

The entry has Shown to
No roles, and its screen is gated by role_required The accounts the screen lets in
No roles, and its screen is not gated Everyone its section is for, unless an access policy for the endpoint refuses the account
roles The accounts with one of those roles, or that a policy for the endpoint lets in. They replace the screen’s roles
An href and no endpoint Everyone its section is for, or the accounts with one of its roles

Name roles only for an entry narrower than its screen. An inactive account sees only the entries without roles and without a gated screen.

Marking the current entry

register_menu_item("admin", _l("Admin"), endpoint="admin.dashboard", section="admin", match="admin.")

The current entry gets active set to True and aria_current set to "page". An entry is current when the request’s endpoint starts with its match, which is its endpoint by default. The longest match of the whole menu wins, so admin.users beats an Admin entry matching every admin. screen.

A whole blueprint is its name and a dot. match="admin" would also match admin_tools.index, so a match without a dot logs a warning.

Marking another feature’s entry as current

from splent_framework.nav.menu_registry import register_menu_match


def init_feature(app):
    register_menu_match("notes", "reports.")

When your feature adds screens under an entry it does not own, register_menu_match makes that entry current on them too. It works in the sidebar and the user menu, whichever feature loads first, and survives a refiner registering the entry again.

Showing a badge

A badge is a value next to the label, usually a count. Pass a function with no arguments and it is called only for an entry the account sees, once per request. None, 0 and "" show nothing, and a function that raises shows nothing and logs a warning.

Adding a section

from splent_framework.nav.menu_registry import register_menu_section

register_menu_section("research", _l("Research"), 150)

Each entry belongs to a section, main by default, and the section says who it is for. The default sections use orders 50 to 500, so yours fits between them. Pass audience="everyone" or "anonymous" for a section that visitors see. A label of "" gives a section without a heading.


Drawing the menus in a shell

<ul class="sidebar-nav">
  {% for section in menu_sections() %}
    {% if section.label %}<li class="sidebar-header">{{ section.label }}</li>{% endif %}
    {% for item in section.entries %}
      <li class="sidebar-item{{ ' active' if item.active }}">
        <a class="sidebar-link" href="{{ item.url }}"
           {% if item.aria_current %}aria-current="{{ item.aria_current }}"{% endif %}
           {% if item.external %}target="_blank" rel="noopener"{% endif %}>
          {{ item.label }}
          {% if item.badge %}<span class="badge">{{ item.badge }}</span>{% endif %}
        </a>
      </li>
    {% endfor %}
  {% endfor %}
</ul>

menu_sections() gives the sidebar’s sections with something to show, in order. Read section.entries, because section.items is the dict’s own method. user_menu_sections() gives the account’s dropdown in the same shape. Both resolve once per request, however often the shell reads them.


Hiding and reordering entries in your product

[tool.splent.layout.menu]
hide = ["notes"]
order = { notes_review = 10, user_notes = 5 }

Your product hides and reorders entries by key, without touching any feature. Both options apply to the sidebar and the user menu. A hidden entry is never shown and its badge is never asked.

The table is read when the app starts, so restart after a change. A malformed table stops the app and names the option. A key no entry has is ignored, and product:validate warns about it, which catches a typo or a feature that left the product.


Moving a shell from menu slots to the registry

A shell that draws the menu slots, such as layout.anonymous_sidebar, shows entries features write as markup. A feature that registers its entries and still fills its slot would show each entry twice, so a shell that draws the registry reads its menu slots through menu_slot(name), which leaves out the features that have entries.

  1. Each feature registers its entries and keeps its menu hooks for one minor version.
  2. Your product moves its shell to the registry in the change that pins those versions.
  3. The next minor of each feature drops its menu hooks.
{% for hook in menu_slot("layout.sidebar.authenticated.items") %}{{ hook() | safe }}{% endfor %}

The scaffolded base_template.html draws the registry and, after it, the menu slots of the features without entries. While the registry has nothing for the account, the menu slots are the whole menu. Its other slots are not menus, see What the application shell provides.


Choosing a page’s layout

{% extends shell('app') %}

{% block content %}
  <h1>Notes</h1>
{% endblock %}

shell(name) returns the template a page extends, so a page names its shell instead of a file. Your product can then point a shell at another layout and no page changes.

Name Resolves to Unless
app base_template.html SPLENT_SHELL_APP names another template
public public_base.html SPLENT_SHELL_PUBLIC names another template
login The app shell AUTH_LOGIN_LAYOUT names a template

Set them in [tool.splent.config]. They move only the pages that extend shell(...), the framework’s 403 page among them. A page that names a file, such as {% extends "base_template.html" %}, stays in that file.

The template a shell setting names must extend a file, never that same shell. A layout that extends shell('app') while SPLENT_SHELL_APP names it extends itself, and the page fails with RecursionError.


What the application shell provides

A feature’s page extends shell('app') without knowing which template is behind it. So every template a product puts there provides these blocks and slots.

Block Holds
title The page’s name. The shell adds the site’s name to <title>. It defaults to the variable title, so {% set title = ... %} works too
head_extra and head Tags the page adds to <head>
breadcrumb The page’s trail, above its content
content The page
scripts Scripts at the end of <body>, after layout.scripts

The shell draws the sidebar from menu_sections() and the account menu from user_menu_sections(). It opens these slots for widgets, none of them a menu.

Slot Where For example
layout.head.css <head>, after the shell’s stylesheets A feature’s stylesheet
layout.header.menu The header bar, before its buttons A search box
layout.navbar.items The header’s buttons, before the account menu An export button
layout.navbar.user The top of the account menu, for a signed-in account Who is signed in
layout.footer The footer Links and credits
layout.scripts The end of <body>, before the scripts block A feature’s script bundle

The button that opens the account menu is the shell’s, and so is the divider under layout.navbar.user, drawn only when the slot renders something. A feature that fills the slot draws neither. The base_template.html that product:create writes provides all of this, and the template system lists its slots.


Loading assets per shell

from splent_framework.assets.asset_registry import register_asset

register_asset(
    "css", "skin_ocean.assets", order=200, shell="app",
    subfolder="css", filename="admin_ocean.css",
)

shell says which shell loads the file, "public" by default, "app" or "both". Register the same asset again for the other shell and it serves both. scope="blueprint" loads it only on the pages of its own blueprint, for a library whose styles would leak into every page.

A shell draws its assets with render_assets("css", shell="app"), or reads their URLs with get_assets. Each returns the assets of that shell plus those for "both", in order and without repeats. Without shell, the answer is the public shell’s.


Using the CSP nonce

<script nonce="{{ csp_nonce() }}" src="{{ href }}"></script>

csp_nonce() returns the nonce of the request being served, 128 random bits, the same for every call within the request. Put it on the tags your template owns.

The policy composed per page carries the nonce in script-src and style-src. A policy you write in SPLENT_CONTENT_SECURITY_POLICY is sent exactly as written, so there the attribute does nothing until your policy asks for it.


Advanced

The registries belong to the process. When two apps are built in one process, as in a test session, the last one built wins and both serve its entries.

Outside a request, as in a mail, nobody is signed in and nothing is current, and an endpoint entry is left out unless SERVER_NAME is set. Outside any app context the menus are empty and csp_nonce() raises RuntimeError, as flask.g does.

A sign-in page that extends config.AUTH_LOGIN_LAYOUT or "base_template.html" instead of shell('login') ignores SPLENT_SHELL_APP. When you move the application shell, set AUTH_LOGIN_LAYOUT too.

A screen gated by a decorator that drops the view’s attributes hides its roles from the menu. Write that decorator with functools.wraps, or name roles on the entry. Under two stacked role_required, the entry takes the roles both accept.


Reference

register_menu_item and register_user_menu_item

Both in splent_framework.nav.menu_registry, with the same arguments. A user menu entry’s default section is account.

Argument Default Meaning
key Required Stable identifier. The product hides and orders by it, and registering it again replaces the entry
label Required A lazy string, a plain string translated when drawn, or a function with no arguments
endpoint None The endpoint it opens. Give this or href, not both
href None A URL, used as written
icon None An icon name
section "main" The section it belongs to
order 100 Lower first within the section, ties by key
roles None The roles that see it, in place of its screen’s. One role may be a string
badge None A value, or a function with no arguments
match The endpoint Keyword only. The endpoint prefix, or a tuple of them, that make it current
external False Keyword only. The shell opens it in a new tab with target="_blank" and rel="noopener"

register_menu_match(key, match) takes an entry’s key and a prefix, or several. It raises ValueError for an empty key or no prefix.

register_menu_section

Argument Default Meaning
key Required The name entries use in section
label Required The heading, translated like a label. "" or None for none
order 100 Lower first
audience "signed_in" Keyword only. "signed_in", "anonymous" or "everyone"

Default sections

Key Heading Order For
site None 50 Everyone, signed in or not
main Menu 100 Signed-in accounts
admin Administration 200 Signed-in accounts
developer Developer 300 Signed-in accounts
account Account 400 Signed-in accounts
anonymous Get started 500 Visitors who are not signed in

The headings ship translated in the framework’s catalog. An entry with roles in a section for visitors raises ValueError, and one whose screen is gated is never shown there, with a warning.

Reading the menus

Function Returns
menu(section="main") The entries of one sidebar section the account sees
menu_sections() [{"key", "label", "entries"}], the sidebar’s sections with something to show, in order. label is "" for a section without a heading
user_menu() Every user menu entry the account sees
user_menu_sections() The user menu grouped by section, in the same shape
menu_slot(name) The callbacks of the slot name whose features register no menu entry
unknown_menu_keys(app=None, layout=None) The keys of the product’s table that no entry has
parse_layout_menu(raw) The table checked and normalized, or ValueError
clear_menus() Empties both menus and restores the default sections, for tests

required_roles(view), in splent_framework.decorators.decorators, gives the roles role_required asks for on a view, () for none, or None when it does not gate the view.

Each entry is a dict with these keys.

Key Holds
key, label, url, icon, section The entry’s key, translated text, URL, icon name and section
active True on the current entry
aria_current "page" on the current entry, else None
badge The badge value, or None
external True for an entry the shell opens in a new tab

menu, menu_sections, menu_slot, user_menu, user_menu_sections, shell and csp_nonce are globals of every template, next to the others.

Errors

Call Raises ValueError when
register_menu_item, register_user_menu_item The key is empty, both endpoint and href are given or neither, or order is not a whole number
register_asset(..., shell=...) shell is not "public", "app" or "both"
get_assets(kind, shell=...), render_assets shell is not "public" or "app", the shell rendering the page
shell(name) name is not "app", "public" or "login"

See also


Back to top

splent. Distributed by an LGPL license v3. Contact us: drorganvidez@us.es