site
Configure and build a documentation website
A Site combines pages, shared settings, and optional generated files. Use Site.from_dir to read Markdown, notebooks, and octavo.yml from a source directory. Pass keyword arguments to override file settings.
Page settings inherit from the site and ancestor directory indexes. A page’s own frontmatter takes precedence. Header navigation comes from nav-links; sidebar navigation comes from source directories, or from sidebar-links when set.
Site.build writes HTML and Markdown pages, assets, redirects, and a Pagefind search index. It also writes a sitemap and robots.txt when site-url is configured. Every other visible file in the source directory is copied as an asset; list glob patterns in the exclude setting to leave paths out of the site. Links between pages are relative and resolve separately for HTML and Markdown output.
octavo.site turns a directory of markdown files and notebooks into a static website, with navigation, search, and a markdown version of each page. It combines the documents read by octavo.pages with the rendering in octavo.core and the layout and assets in octavo.theme.
Use Site.from_dir to read markdown files, notebooks, and settings from octavo.yml, then build to write the site.
site = Site.from_dir('docs', title='My project')
missing = site.build(out='_site') # writes to _site in the working directory
Keyword settings passed to from_dir override octavo.yml. If you already have Page objects, use Site(pages, **settings) instead.
The sidebar follows the source directories. Content links can refer to source files, such as api/01_config.ipynb; the build converts them to the corresponding HTML or markdown destinations. build returns a dictionary of pages with unresolved document links rather than failing on those links.
YAML output is relative to octavo.yml; explicit Python output paths are relative to the working directory. Each build deletes the existing output directory before writing, so use a directory containing only generated files. The result can be deployed to static hosting; this module does not serve or watch the site.
Settings
Settings follow Quarto's names and meanings. Write them with hyphens in octavo.yml and frontmatter, as Quarto does. Python code uses underscores, because snake_keys converts the keys as Octavo reads them: toc-depth in a file is toc_depth here.
DEFAULTS lists the settings a page can inherit, with the values used when neither the site nor the page sets them:
toc: falseleaves out the table of contents.toc-depthis the number of heading levels the table of contents shows, counting#as the first, as Quarto does. The default3shows##and###headings, and1shows none. Octavo counts from the level of a page's top sections, so on a page whose sections start at###, it shows one level more than Quarto.sidebar: falsehides a page's sidebar and leaves the page out of the sidebar's tree.page-layout: customgives a page a layout of its own, as described in Custom layout.css,jsandpagetitleadd a stylesheet, a script and a browser tab title, also described there.mathsets the inline maths syntax thatmd2docreads. Setmath: dollarsinoctavo.ymlto read$…$as maths, as Quarto does.
Page settings
Create a Site from Page objects and shared settings, or use Site.from_dir to read them from a source directory. When constructing a site directly, pass root to copy assets from that directory. Without root, no source assets are copied. Explicit Python output paths use the current working directory.
Only the settings listed in DEFAULTS inherit from the site and directory indexes to individual pages. Octavo ignores settings it doesn't read, but build warns about unrecognised site settings, such as a misspelt toc-dept. unknown_keys lists them.
Site
def Site(
pages:list, # The site's `Page`s
root:str=None, # Source directory for copying assets
files:list[octavo.pages.GeneratedFile]=None, # to write verbatim to the output
**settings
):
A collection of pages, generated files, and site settings
Site.discoverable_pages
def discoverable_pages():
Pages included in discovery outputs, without changing the complete page collection
Site.discoverable
def discoverable(
page:octavo.pages.Page
):
Whether page appears in generated navigation, listings, feeds, sitemap and search
A directory’s _metadata.yml file or index page can set defaults for pages below it. Resolving those settings requires the directory metadata, indexes, and a list of each page’s ancestors.
opts resolves page settings in this order: built-in defaults, site settings, ancestor directory _metadata.yml files and directory indexes from shallowest to deepest, then the page’s own frontmatter. Later values override earlier ones. Only keys in DEFAULTS are inherited. Page-specific metadata such as title and description stays on its original page.
Site.opts
def opts(
page, # Page to resolve settings for
):
Settings for page: defaults < site < directory _metadata.yml and indexes < page frontmatter
This example site has a homepage, a getting-started page, and tutorial, explanation, and API directories. The site-wide table of contents depth is 2.
config = Page('api/01_config.md', '---\ntitle: config\norder: 1\n---\n')
directives = Page('explanations/directives.md', '---\ntitle: Directives\norder: 2\ntoc-depth: 1\n---\n')
pages = [Page('index.md', '---\ntitle: nbdev\nsidebar: false\n---\n'),
Page('getting_started.md', '---\ntitle: Getting Started\n---\n'),
Page('tutorials/index.md', '---\ntitle: Tutorials\norder: 2\n---\nTutorials.\n'),
Page('tutorials/tutorial.md', '---\ntitle: End-To-End Walkthrough\norder: 1\n---\n'),
Page('explanations/index.md', '---\ntitle: Explanations\norder: 3\n---\nExplanations.\n'),
directives,
Page('api/index.md', '---\ntitle: API\norder: 9\n---\nAPI.\n'),
config,
Page('api/02_maker.md', '---\ntitle: maker\norder: 2\n---\n')]
site = Site(pages, title='nbdev', toc_depth=2)
site
Site(9 pages)
The config page does not set toc-depth, so it inherits 2 from the site.
site.opts(config)
{ 'css': None,
'js': None,
'math': 'brackets',
'page_layout': None,
'pagetitle': None,
'sidebar': True,
'toc': True,
'toc_depth': 2}
A page's frontmatter overrides site settings for that page. directives.md sets toc-depth: 1, which Python code reads as toc_depth.
test_eq(site.opts(directives).toc_depth, 1)
test_eq(site.opts(config).toc_depth, 2)
site.opts(directives)
{ 'css': None,
'js': None,
'math': 'brackets',
'page_layout': None,
'pagetitle': None,
'sidebar': True,
'toc': True,
'toc_depth': 1}
Without a configured toc-depth, a page uses Quarto's default of 3.
plain = Site(pages)
test_eq(plain.opts(config).toc_depth, 3)
plain.opts(config)
{ 'css': None,
'js': None,
'math': 'brackets',
'page_layout': None,
'pagetitle': None,
'sidebar': True,
'toc': True,
'toc_depth': 3}
The site title and page title remain separate. Neither is returned by opts, because title is not an inherited page setting.
test_eq(site.opts(config).get('title'), None)
site.settings.title, config.title
('nbdev', 'config')
Site navigation
The page tree is derived from the source directories. Each directory's index page supplies its title and order. A directory without an index uses its directory name. Root pages precede directory sections.
sidebar: false hides a page's sidebar and excludes it from the tree. On a directory index, it applies to the directory's pages through the settings cascade. Primary navigation remains in the header. A page can appear in both the header and sidebar.
A section's heading links to its index page when one exists. The disclosure marker expands or collapses its links. All sidebar sections start open.
Section
def Section(
dir:str, # Directory the pages sit in, relative to the source root
index:octavo.pages.Page, # Its `index` page, where it has one
pages:list, # Its direct child pages
sections:list=(), # Its child `Section`s
):
A directory of pages and nested subsections, headed by its own index page
Site.sections
def sections():
The site's root pages and recursive directory sections in the sidebar
The homepage sets sidebar: false and is omitted from the tree. Getting Started appears before the directory sections because root pages are sorted separately. The directory indexes set the order of Tutorials, Explanations, and API.
test_eq([o.title for o in site.sections], ['Getting Started','Tutorials','Explanations','API'])
site.sections
[getting_started.md -> getting_started.html, Tutorials -> tutorials/index.html (1 pages), Explanations -> explanations/index.html (1 pages), API -> api/index.html (2 pages)]
A relative link gives directions from the current page's folder. For example, from api/config.html:
maker.htmlopens another page in the sameapi/folder.../tutorials/tutorial.htmlgoes up one folder (../), then intotutorials/.
These directions stay the same whether the site is hosted at example.com/ or example.com/myproject/. relhref(src, dst) calculates this relative link from the two pages' paths within the site.
relhref
def relhref(
src:str, dst:str
):
Link to page dst from a page at src, both given relative to the site root
From api/config.html, api/maker.html becomes maker.html. A tutorial in another directory requires a ../tutorials/ prefix.
test_eq(relhref('api/config.html', 'api/maker.html'), 'maker.html')
test_eq(relhref('index.html', 'api/config.html'), 'api/config.html')
relhref('api/config.html', 'tutorials/tutorial.html')
'../tutorials/tutorial.html'
Configured navigation omits links to unlinked drafts, including their aliases. A group whose own link targets a draft keeps its label and any published children. Empty groups are removed. External links and links written in page content are unchanged.
filter_nav
def filter_nav(
items, hidden
):
Remove local targets in hidden from a navigation tree, retaining nonempty groups
Site.visible_links
def visible_links(
items
):
Configured navigation items without links to undiscoverable pages
navigation renders the derived page tree in the sidebar. Links are relative to the current page. The current page has aria-current="page". Groups use native details and summary elements.
Site.navigation
def navigation(
page:octavo.pages.Page, # Page whose navigation this is
):
The sidebar as a Nav FT: sidebar_links when set, otherwise the derived document tree, or None
The config page’s navigation marks its current entry with aria-current="page". Links within api/ use local filenames; tutorial links use ../tutorials/.
bar = str(site.navigation(config))
assert 'aria-current="page"' in bar
assert 'href="../index.html"' not in bar
assert '<a href="../tutorials/tutorial.html">' in bar
assert '<a href="maker.html">' in bar
assert '<details open><summary><a href="index.html">API</a></summary>' in bar
assert '<details open><summary><a href="../tutorials/index.html">Tutorials</a></summary>' in bar
assert '>Overview</a>' not in bar
bar
'<nav aria-label="Site"><ul><li><a href="../getting_started.html">Getting Started</a></li><li><details open><summary><a href="../tutorials/index.html">Tutorials</a></summary><ul><li><a href="../tutorials/tutorial.html">End-To-End Walkthrough</a></li></ul></details></li><li><details open><summary><a href="../explanations/index.html">Explanations</a></summary><ul><li><a href="../explanations/directives.html">Directives</a></li></ul></details></li><li><details open><summary><a href="index.html">API</a></summary><ul><li><a href="config.html" aria-current="page">config</a></li><li><a href="maker.html">maker</a></li></ul></details></li></ul></nav>'
A project can list its sidebar instead, in the sidebar-links setting. Items use the format of nav-links, described under the site header below. When sidebar-links is set, the sidebar shows exactly these items in this order, in place of the tree derived from directories. An item without text takes the title of the page at its href. This suits a hand-written sidebar, such as a Quarto sidebar.yml that groups pages from one directory into sections:
listed = Site(pages, sidebar_links=[dict(href='getting_started.html'),
dict(text='Reference', children=[dict(href='api/config.html'), dict(href='explanations/directives.html')])])
bar = str(listed.navigation(config))
assert '<details open><summary>Reference</summary>' in bar
assert '<a href="config.html" aria-current="page">config</a>' in bar
assert 'tutorial.html' not in bar
bar
'<nav aria-label="Site"><ul><li><a href="../getting_started.html">Getting Started</a></li><li><details open><summary>Reference</summary><ul><li><a href="config.html" aria-current="page">config</a></li><li><a href="../explanations/directives.html">Directives</a></li></ul></details></li></ul></nav>'
Loading site configuration
Site.from_dir('docs') reads markdown files and notebooks under docs/ and loads settings from docs/octavo.yml if it exists. Pass keyword arguments to override individual settings without editing the file—for example, Site.from_dir('docs', toc_depth=1) overrides toc_depth from the YAML configuration.
read_cfg returns output as an absolute Path, resolved relative to the directory containing octavo.yml. Python keyword overrides are applied afterward. An output passed to Site or Site.from_dir is relative to the working directory at that call; an out passed to build is relative to the working directory at build time.
Site.from_dir
def from_dir(
root:str, # Directory of source documents, or a Python project root
nbproc=None, # Optional callable applied to notebooks before conversion
mdproc=None, # Optional callable `(text, rel) -> text` applied to every page's Markdown
scripts:bool=True, # Execute double-suffix render scripts (`*.md.py`, `*.svg.py`) under `root`?
py_docs:bool=True, # Discover Python package API pages, defaults, symbol links, and `llms.txt` when `pyproject.toml` is present?
doc_renderer=None, # Optional renderer passed to `expand_docs` for `{{< doc ... >}}` shortcodes
**settings
):
Read a site from root, with keyword settings overriding octavo.yml and pyproject.toml
read_cfg
def read_cfg(
root:str
):
Read octavo.yml with snake-case keys and an absolute output path; absent or empty files give {}
parse_cfg
def parse_cfg(
text:str, root:str='.', path:str='octavo.yml'
):
Parse octavo.yml YAML text into snake-case settings with an absolute output path; empty text gives {}
This source directory sets the site title, table of contents depth, output directory, and favicon in octavo.yml. Its exclude setting keeps the drafts directory out of the site: its documents are not pages, and its other files are not copied. See source_files for the pattern rules.
_root_td = tempfile.TemporaryDirectory()
root = Path(_root_td.name)/'docs'
root.mkdir()
(root/'octavo.yml').write_text('title: nbdev\ntoc-depth: 2\noutput: ../_site\nfavicon: favicon.png\nexclude: [drafts]\n')
(root/'index.md').write_text(r'''---
title: Home
---
A_name starts with [config](api/01_config.md).
```python
items = ["a_b"]
```
\[x_1 + y_2\]
''')
(root/'api').mkdir()
(root/'api/01_config.md').write_text('---\ntitle: config\naliases:\n - /configuration.html\n---\n\n## Reading\n\nWhere it looks.\n\n### Search order\n\nWhich file wins.\n')
(root/'images').mkdir()
(root/'images/logo.svg').write_text('<svg/>')
(root/'drafts').mkdir()
(root/'drafts/plan.md').write_text('# Plan\n')
(root/'drafts/notes.txt').write_text('notes\n')
built = Site.from_dir(root)
test_eq(built.pages.attrgot('rel'), ['api/01_config.md', 'index.md'])
test_eq(built.settings.title, 'nbdev')
test_eq(built.opts(built.pages[0]).toc_depth, 2)
test_eq(built.settings.output, root.parent.resolve()/'_site')
{k:v for k,v in built.settings.items() if k!='output'}
{'title': 'nbdev',
'toc_depth': 2,
'favicon': 'favicon.png',
'exclude': ['drafts']}
Passing toc_depth=1 overrides the file’s value of 2 while retaining its title.
over = Site.from_dir(root, toc_depth=1)
test_eq(over.settings.toc_depth, 1)
test_eq(over.settings.title, 'nbdev')
{k:v for k,v in over.settings.items() if k!='output'}
{'title': 'nbdev',
'toc_depth': 1,
'favicon': 'favicon.png',
'exclude': ['drafts']}
octavo.yml holds a mapping of settings. An empty file gives none, and a list or a single value is an error:
with expect_fail(ValueError, regex='mapping'): parse_cfg('- title: nbdev\n')
test_eq(parse_cfg(''), {})
Additional links and the site header
Use nav-links in octavo.yml to add links and dropdown groups to the site header:
nav-links:
- text: Get started
href: getting_started.html
- text: Help
children:
- text: Report an Issue
href: https://github.com/fastai/nbdev/issues
Each item's text is its visible label. Add href for a link or children for a group; an item can have both, and groups can be nested.
For internal links, use the generated HTML path relative to the site root, such as api/config.html, not the source path api/01_config.ipynb. Octavo makes these links relative to the current page. External URLs, mailto: links, and same-page anchors are left unchanged.
Site.header
def header(
page:octavo.pages.Page, # Page whose header this is
):
The site brand (title and/or logo), primary navigation, icon links, and search control
Site.tools
def tools(
page:octavo.pages.Page, # Page whose tools these are
):
The site's declared icon links followed by its search control
Site.home
def home():
The site's root index page, where it has one
Header navigation can contain nested groups. Hiding a page’s sidebar does not remove its header links.
cfg = dict(title='nbdev', nav_links=[dict(text='Get Started', href='getting_started.html'),
dict(text='Help', children=[
dict(text='Report an Issue', href='https://github.com/fastai/nbdev/issues'),
dict(text='Using nbdev', children=[dict(text='Start here', href='getting_started.html')])])])
navsite = Site(pages, **cfg)
sidebar = str(navsite.navigation(config))
assert 'getting_started.html' in sidebar and 'Help' not in sidebar
bar = str(navsite.header(config))
assert '<a href="../getting_started.html">Get Started</a>' in bar
assert '<a href="https://github.com/fastai/nbdev/issues">' in bar
assert '<summary>Help</summary>' in bar and '<summary>Using nbdev</summary>' in bar
excluded = Page('private.md', '---\ntitle: Private\nsidebar: false\n---\n')
private_site = Site(pages+[excluded], **cfg)
assert 'Private' not in str(private_site.navigation(config))
assert not private_site.navigation(excluded)
assert 'Get Started' in str(private_site.header(excluded))
bar
'<header class="site-header"><a href="../index.html">nbdev</a><details class="header-nav" open><summary>Menu</summary><nav aria-label="Primary"><ul><li><a href="../getting_started.html">Get Started</a></li><li><details><summary>Help</summary><ul><li><a href="https://github.com/fastai/nbdev/issues">Report an Issue</a></li><li><details><summary>Using nbdev</summary><ul><li><a href="../getting_started.html">Start here</a></li></ul></details></li></ul></details></li></ul></nav></details><div class="site-tools"><pagefind-modal-trigger compact></pagefind-modal-trigger></div></header>'
The site header contains its name, primary navigation, icon links, and search trigger. Its name links to the home page when one exists. The search dialog belongs to the page body.
bar = str(Site(pages, title='nbdev').header(config))
assert '<a href="../index.html">nbdev</a>' in bar
assert '<pagefind-modal-trigger compact>' in bar
assert '<pagefind-modal>' not in bar
Site([config], title='nbdev').header(config)
'<header class="site-header"><span>nbdev</span><div class="site-tools"><pagefind-modal-trigger compact></pagefind-modal-trigger></div></header>'
tools declares the icon links beside search in the site header:
tools:
- icon: github
href: https://github.com/fastai/nbdev
label: GitHub
- icon: images/forum.svg
href: https://forums.fast.ai
label: Forum
Bundled ICONS inherit the header's text colour. Paths and URLs render as images. Each link's label provides its accessible name and tooltip. The icon name is the default label.
toolsite = Site(pages, title='nbdev', tools=[dict(icon='github', href='https://github.com/fastai/nbdev', label='GitHub'),
dict(icon='images/forum.svg', href='https://forums.fast.ai', label='Forum')])
bar = str(toolsite.header(config))
assert 'aria-label="GitHub"' in bar and '<img src="../images/forum.svg"' in bar
assert bar.index('aria-label="GitHub"') < bar.index('<pagefind-modal-trigger compact>')
toolsite.tools(config)
'<div class="site-tools"><a href="https://github.com/fastai/nbdev" aria-label="GitHub" title="GitHub"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg></a><a href="https://forums.fast.ai" aria-label="Forum" title="Forum"><img src="../images/forum.svg" alt=""></a><pagefind-modal-trigger compact></pagefind-modal-trigger></div>'
An unknown icon name raises KeyError. Use a bundled name or an image path or URL.
with expect_fail(KeyError, regex='gitlab'): Site(pages, tools=[dict(icon='gitlab', href='https://gitlab.com')]).tools(config)
Links in the content
Links between pages can use either the source path or the generated HTML path. For example, these refer to the same page:
[Maker](/api/02_maker.ipynb#usage)
[Maker](/api/maker.html#usage)
Octavo identifies the target page and chooses the link for each output format: HTML output links to maker.html#usage, while markdown output links to maker.md#usage. Writing .html in a local link does not restrict it to HTML output.
Paths starting with / are relative to the source root. Other paths are relative to the current source file’s directory. A directory path such as /tutorials links to that directory’s index page.
Full URLs, such as https://example.com/api/maker.html, stay unchanged.
Site.by_path
def by_path():
Map extensionless source and output paths, including index directories, to pages
Document extensions are removed during lookup. Asset extensions are retained to distinguish, for example, docs.svg from docs.md.
External URLs, mail addresses, and same-page anchors remain unchanged. Unresolved document links are recorded in missing. Relative unresolved links retain their original address. Root-relative paths are made relative to the current page, including paths to images and downloads.
Linker
def Linker(
site, # The `Site` being built
page:octavo.pages.Page, # Page the addresses sit on
ext:str='html', # Extension of the output being written
assets:set=None, # Static asset paths relative to the site root
):
Resolve page links for an output format and collect unresolved document addresses in missing.
Site.linker
def linker(
page:octavo.pages.Page, # Page containing the links
ext:str='html', # Extension of the output being written
assets:set=None, # Static asset paths relative to the site root
):
A Linker for page
Source filenames, generated filenames, and directory paths resolve to the same pages. URL fragments such as #usage are retained.
Here's an example for a site with the following file tree:
.
├── index.md
├── getting_started.md
├── tutorials/
│ ├── index.md
│ └── tutorial.md
├── explanations/
│ ├── index.md
│ └── directives.md
└── api/
├── index.md
├── 01_config.md ← current page
└── 02_maker.md
lk = site.linker(config)
test_eq(lk('02_maker.ipynb'), 'maker.html')
test_eq(lk('/api/02_maker.ipynb#usage'), 'maker.html#usage')
test_eq(lk('/tutorials'), '../tutorials/index.html')
/explanations/directives.svg remains an image link even though directives.md is a page. Root-relative asset paths become relative to the current page.
test_eq(lk('/explanations/directives.svg'), '../explanations/directives.svg')
{a: lk(a) for a in ['/images/logo.svg', '/explanations/directives.svg']}
{'/images/logo.svg': '../images/logo.svg',
'/explanations/directives.svg': '../explanations/directives.svg'}
gone.ipynb names no known page. It is recorded in missing and left unchanged. External URLs and same-page anchors are not recorded as missing documents.
test_eq(lk('https://fast.ai'), None)
test_eq(lk('#top'), None)
test_eq(lk('gone.ipynb'), None)
test_eq(lk.missing, ['gone.ipynb'])
lk
Linker(api/config.html -> .html, 1 missing)
For Markdown output, the same page lookup produces .md destinations. Asset filenames do not change.
mdlk = site.linker(config, ext='md')
test_eq(mdlk('02_maker.ipynb'), 'maker.md')
test_eq(mdlk('/images/logo.svg'), '../images/logo.svg')
{a: mdlk(a) for a in ['02_maker.ipynb', '/tutorials', '/images/logo.svg']}
{'02_maker.ipynb': 'maker.md',
'/tutorials': '../tutorials/index.md',
'/images/logo.svg': '../images/logo.svg'}
Local document addresses resolve separately for HTML and Markdown, preserving queries and fragments. Absolute URLs express an explicit destination and stay unchanged, even when they point to the configured production site.
published = Site(pages, site_url='https://nbdev.fast.ai/docs/')
for ext in ['html', 'md']:
local_link = published.linker(config, ext=ext)
test_eq(local_link('/api/config.html?view=full#get_config'), f'config.{ext}?view=full#get_config')
test_eq(local_link('/?view=full#intro'), f'../index.{ext}?view=full#intro')
for addr in ['https://nbdev.fast.ai/docs/api/config.html#get_config',
'https://nbdev.fast.ai/docs/', 'https://pypi.org/project/nbdev/',
'//nbdev.fast.ai/docs/api/config.html', 'mailto:info@example.org']:
test_eq(local_link(addr), None)
test_eq(local_link.missing, [])
with tempfile.TemporaryDirectory() as td:
r = Path(td)
(r/'DEV.md').write_text('# Dev')
(r/'nbs/static.html').mk_write('<p>hi</p>')
(r/'nbs/secret.md').mk_write('# Secret')
s = Site([Page('index.md', '# Home')], root=r/'nbs', exclude=['secret.md'])
s._repo_root, s._repo_blob = r, 'https://github.com/org/repo/blob/main/'
lk = s.linker(s.pages[0])
test_eq(lk('./static.html'), None)
test_eq(lk('DEV.md#setup'), 'https://github.com/org/repo/blob/main/DEV.md#setup')
test_eq(lk('secret.md'), None)
test_eq(lk.missing, ['secret.md'])
Redirects
If you move tutorial.md to tutorials/tutorial.md, existing links to tutorial.html would break. For backward compatibility you can add its old address to the new page’s frontmatter:
aliases:
- /tutorial.html
The build writes a redirect at tutorial.html that sends visitors to tutorials/tutorial.html.
Aliases are paths relative to the site root, not full URLs. You can omit the .html extension: /tutorial and /tutorial.html create the same redirect file. An alias ending in / names a folder: /old/guides/ creates old/guides/index.html.
Site.redirects
def redirects():
Map alias output paths to current page destinations
alias_path
def alias_path(
a:str
):
The file an alias a names, relative to the site root
The tutorial now lives at tutorials/tutorial.html. Its alias preserves the old /tutorial.html URL.
moved = Page('tutorials/tutorial.md', '---\ntitle: End-To-End Walkthrough\naliases:\n - /tutorial.html\n---\n')
test_eq(Site([moved]).redirects, {'tutorial.html': 'tutorials/tutorial.html'})
Site([moved]).redirects
{'tutorial.html': 'tutorials/tutorial.html'}
A redirect page uses a meta refresh to open the new destination without JavaScript. It also includes a canonical link and a visible link. The destination is relative to the redirect page, allowing deployment below a project path.
redirect_html
def redirect_html(
src:str, dst:str
):
A stub page at src that sends a reader to dst, both relative to the site root
The redirect at tutorial.html points to tutorials/tutorial.html.
stub = redirect_html('tutorial.html', 'tutorials/tutorial.html')
assert 'url=tutorials/tutorial.html' in stub
print(stub)
<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<title>Redirected</title>
<link rel="canonical" href="tutorials/tutorial.html">
<meta http-equiv="refresh" content="0; url=tutorials/tutorial.html">
</head>
<body><p>This page has moved to <a href="tutorials/tutorial.html">tutorials/tutorial.html</a>.</p></body></html>
The redirect at old/guides/tutorial.html points to ../../tutorials/tutorial.html.
deep = redirect_html('old/guides/tutorial.html', 'tutorials/tutorial.html')
assert 'href="../../tutorials/tutorial.html"' in deep
paths = {a: alias_path(a) for a in ['/tutorial', '/tutorial.html', '/old/guides/', '/']}
test_eq(paths['/old/guides/'], 'old/guides/index.html')
paths
{'/tutorial': 'tutorial.html',
'/tutorial.html': 'tutorial.html',
'/old/guides/': 'old/guides.html',
'/': 'index.html'}
Sitemap
A sitemap helps search engines discover your published pages. To generate one, set the site's public address in octavo.yml:
site-url: https://example.com/docs
For a page written to api/config.html, the generated sitemap.xml contains https://example.com/docs/api/config.html. Include any deployment subdirectory, such as /docs, in site-url.
The build also writes a robots.txt that names the sitemap, as Quarto does, unless the source directory supplies its own. Crawlers read robots.txt only at the root of a host, so it has an effect only when the site is served from a domain root.
Site.robots
def robots():
Return robots.txt text naming the sitemap, or an empty string when site_url is unset
Site.sitemap
def sitemap():
Return sitemap XML, or an empty string when site_url is unset
Site.abs_url
def abs_url(
dest:str
):
With site_url="https://nbdev.fast.ai", the config page is listed as https://nbdev.fast.ai/api/config.html.
mapped = Site(pages, title='nbdev', site_url='https://nbdev.fast.ai')
assert '<loc>https://nbdev.fast.ai/api/config.html</loc>' in mapped.sitemap()
test_eq(mapped.robots(), 'Sitemap: https://nbdev.fast.ai/sitemap.xml\n')
print(mapped.sitemap()[:300])
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://nbdev.fast.ai/index.html</loc></url>
<url><loc>https://nbdev.fast.ai/getting_started.html</loc></url>
<url><loc>https://nbdev.fast.ai/tutorials/index.html</loc></url>
<url><l
Without site_url, sitemap and robots return empty strings, and the build writes neither file.
quiet = Site(pages, title='nbdev')
test_eq((quiet.sitemap(), quiet.robots()), ('', ''))
quiet.settings
{'title': 'nbdev'}
Listings and Feeds
A listing adds links to other pages using their frontmatter titles and descriptions. Configure it under listing in the frontmatter of the page where it should appear—not in octavo.yml:
listing:
contents: posts
type: cards
sort: date desc
feed: true
Each setting controls a separate choice:
contentsselects a directory relative to the listing page. Here,postsincludes pages under itsposts/subdirectory. By default, it selects the current directory and its subdirectories. The listing page itself is always excluded.typechoosescards(the default) ortable. Tables show linked titles and descriptions. Cards can also show dates, authors,categories, and images. Each card uses the listed page’s frontmatterimage, or its first body image when none is set.sortdefaults to index pages first, thenorder, then title; missingordervalues are treated as999. Setdate descfor newest first—the only explicit sort mode currently supported.feeddefaults tofalse. Set it totrueto generate an RSS feed atindex.xmlbeside the listing page. This also requiressite-urlinoctavo.yml. The feed contains the same selected pages, always newest first, regardless of the listing’s sort order. To change the feed's own settings, described below withrss_feed, givefeeda block of them in place oftrue.
Use listing: {} to enable a listing with all defaults. The build appends it after the page’s own content in both HTML and markdown output, with links adjusted for each format.
Site.page_image
def page_image(
page:octavo.pages.Page
):
The page's explicit image, else its first non-embedded body image
page_image supplies listings and social previews with the frontmatter image, or the first non-embedded body image. It renders the page's own content, excluding generated listings, the header, and the footer. Paths remain relative to the source page. It works before the page is built and leaves metadata unchanged.
Site.render_listing
def render_listing(
page:octavo.pages.Page
):
The page's listing as Markdown, ready for HTML and GFM
Site.categories_nav
def categories_nav(
page:octavo.pages.Page
):
Render category filters and post counts for a listing page
Site.listing_href
def listing_href(
page:octavo.pages.Page
):
URL from page to the first listing that includes it, or None
Site.listing_pages
def listing_pages(
page:octavo.pages.Page, sort:str=None
):
The selected pages in listing order, unless overridden
This example site has two sections: an API section with an index and one documentation page, and a blog section with an index and two posts.
The indexes configure different listings:
- API:
listing: {type: table}lists pages underapi/in a table. - Blog:
contents: postsselects pages underblog/posts/,sort: "date desc"puts the newest post first, andfeed: truerequests an RSS feed.
The blog index sets sidebar: false and toc: false. Its posts inherit these settings. Each post explicitly restores toc: true for its article headings. You can instead restore it once in blog/posts/index.md. The API section keeps its default sidebar and TOC. Hiding the sidebar also omits the blog and its posts from the derived navigation tree.
Sidebar visibility and listing selection are independent: hiding the blog section from navigation does not exclude its posts from the blog listing.
p_api_idx = Page('api/index.md', '---\ntitle: API\nlisting:\n type: table\n---\n')
p_api_fn = Page('api/01_core.md', '---\ntitle: Core [API]\ndescription: The `core` | functions\n---\n')
p_blog_idx = Page('blog/index.md', '---\ntitle: My Blog Title\nsidebar: false\ntoc: false\nlisting:\n contents: posts\n sort: "date desc"\n feed: true\n---\n')
p_post1 = Page('blog/posts/first-post/index.md', '---\ntitle: First Blog Post\norder: 0\ntoc: true\ndate: "2022-07-28"\nauthor: [Author Two, Author One]\ndescription: First post description\nimage: /images/card.png\ncategories: [release, "Example Category"]\n---\n')
p_post2 = Page('blog/posts/second-post/index.md', '---\ntitle: Second Blog Post\ntoc: true\ndate: "2022-08-25"\nauthor: [{name: Author One, url: "https://example.com/author-one"}, {name: Author Two}, Author Three]\ndescription: Second post [description] with `code` | example\ncategories: [technical]\n---\n{width=88% fig-align="center"}\n\n')
test_site = Site([p_api_idx, p_api_fn, p_blog_idx, p_post1, p_post2], title='TestSite', site_url='https://example.com')
The blog index suppresses its sidebar and TOC. Posts keep the inherited sidebar setting but explicitly restore their own TOCs.
test_eq(test_site.opts(p_api_idx).sidebar, True)
test_eq(test_site.opts(p_blog_idx).sidebar, False)
test_eq(test_site.opts(p_post1).sidebar, False)
test_eq(test_site.opts(p_post2).sidebar, False)
assert not test_site.navigation(p_blog_idx)
assert 'aria-label="Site"' in str(test_site.navigation(p_api_idx))
assert 'My Blog Title' not in [o.title for o in test_site.sections]
test_eq(test_site.opts(p_blog_idx).toc, False)
test_eq(test_site.opts(p_post1).toc, True)
test_eq(test_site.opts(p_post2).toc, True)
The table preserves brackets in its title, a literal pipe in its description, and inline code formatting. Its child link resolves to HTML or Markdown according to the output.
The GFM output escapes the brackets and the pipe, which GitHub renders as the original text.
api_doc = md2doc(test_site.render_listing(p_api_idx))
api_html = str(api_doc.to_html(link=test_site.linker(p_api_idx)))
api_gfm = api_doc.to_gfm(link=test_site.linker(p_api_idx, 'md'))
assert 'core.md' in api_gfm and r'Core \[API\]' in api_gfm and 'The `core` | functions' in api_gfm
assert '<table>' in api_html and 'href="core.html"' in api_html
assert 'Core [API]' in api_html and 'The <code>core</code> | functions' in api_html
assert api_html.count('<td>') == 2
print(api_gfm)
| Title | Description |
|--- |--- |
| [Core \[API\]](core.md) | The `core` | functions |
print(api_gfm)
| Title | Description |
|--- |--- |
| [Core \[API\]](core.md) | The `core` | functions |
Blog cards retain their metadata and newest-first order in both outputs. HTML keeps the card classes and category data; GFM contains ordinary headings, links, paragraphs, and images. The first post uses its explicit cover instead of its body image; the second uses its first body image, including when that image has width and alignment attributes. Image paths are resolved from each post, then made relative to the index.
author accepts a name string, a dictionary with a string name and optional url, or a list mixing those forms. Listing cards link names that have a URL; RSS uses plain names. Author metadata is not modified. The plural authors key and structured name objects are not supported.
blog_doc = md2doc(test_site.render_listing(p_blog_idx))
blog_html = str(blog_doc.to_html(link=test_site.linker(p_blog_idx)))
blog_gfm = blog_doc.to_gfm(link=test_site.linker(p_blog_idx, 'md'))
assert 'class="listing-card"' in blog_html and 'data-categories="|release|example category|"' in blog_html
for rendered in [blog_html, blog_gfm]:
assert 'Second Blog Post' in rendered and 'Author Two, Author One' in rendered
assert 'August 25, 2022' in rendered and 'July 28, 2022' in rendered
assert 'posts/second-post/cover%20image.gif' in rendered and '../images/card.png' in rendered
assert rendered.index('Second Blog Post') < rendered.index('First Blog Post')
assert 'body.png' not in rendered and 'later.png' not in rendered
HTML links target .html; Markdown links target .md. Markdown output retains the description and categories without the HTML layout attributes.
assert 'posts/second-post/index.html' in blog_html
assert 'posts/second-post/index.md' in blog_gfm
assert ':::' not in blog_gfm and 'data-categories' not in blog_gfm
assert '## [Second Blog Post]' in blog_gfm and 'technical' in blog_gfm
assert 'class="listing-category"' in blog_html and '{.listing-' not in blog_gfm and '{:' not in blog_gfm
assert r'Second post \[description\] with `code` | example' in blog_gfm
Linked author dictionaries and plain names can share a byline. Rendering keeps the original author metadata unchanged.
assert 'href="https://example.com/author-one"' in blog_html
assert 'https://example.com/author-one' in blog_gfm
assert 'Author Three' in blog_html and 'Author Three' in blog_gfm
test_eq(p_post2.meta['author'][0]['url'], 'https://example.com/author-one')
print(blog_gfm)
## [Second Blog Post](posts/second-post/index.md)
August 25, 2022 · [Author One](https://example.com/author-one), Author Two, Author Three
Second post \[description\] with `code` | example
[technical](#category=technical)

## [First Blog Post](posts/first-post/index.md)
July 28, 2022 · Author Two, Author One
First post description
[release](#category=release) [Example Category](#category=Example%20Category)

Category filters appear in the article above the listing. Their counts come from the same selected posts.
cat_nav = str(test_site.categories_nav(p_blog_idx))
assert 'All (2)' in cat_nav and 'technical (1)' in cat_nav and 'Example Category (1)' in cat_nav
assert 'aria-label="Filter by category"' in cat_nav
cat_nav
'<nav class="categories-nav" aria-label="Filter by category"><ul><li><a href="#category=" aria-current="true">All (2)</a></li>\n<li><a href="#category=Example%20Category">Example Category (1)</a></li>\n<li><a href="#category=release">release (1)</a></li>\n<li><a href="#category=technical">technical (1)</a></li></ul></nav>'
Site.feed_cfg
def feed_cfg(
page:octavo.pages.Page
):
Feed settings of listing page, with Quarto's defaults for those it doesn't set
A listing with feed set gets an RSS feed of its 20 newest pages, written to index.xml in the listing page's folder. Each item holds the page's whole article, as in Quarto. feed: true uses the defaults. To change them, give feed Quarto's settings:
listing:
contents: posts
feed:
items: 10
type: partial
itemsis the number of pages in the feed. It defaults to20.typesets what each item holds.full, the default, gives the whole article.partialgives the page'sdescription, or its first paragraph if it has none.metadatagives only thedescription.titledefaults to the site'stitle, or to the listing page's title if the site has none.descriptiondefaults to the listing page'sdescription, then the site's, then the feed title.languageadds a language code, such asen. The feed has none by default.
feed_cfg fills in the defaults:
cfg = test_site.feed_cfg(p_blog_idx)
test_eq((cfg['items'], cfg['type'], cfg['title']), (20, 'full', 'TestSite'))
cfg
Site.feed_link
def feed_link(
page:octavo.pages.Page
):
The <link> FT for the feed of page, or None if it has none
Site.feed_dest
def feed_dest(
page:octavo.pages.Page
):
Where the feed of listing page is written, relative to the site root
Browsers and feed readers find a feed through a <link rel="alternate"> tag in a page's head. feed_link gives that Link element for the page that owns the feed, and None for every other page, such as the posts:
test_eq(test_site.feed_link(p_post1), None)
test_eq(str(test_site.feed_link(p_blog_idx)), '<link rel="alternate" type="application/rss+xml" title="TestSite" href="index.xml">')
test_site.feed_link(p_blog_idx)
Site.feed_html
def feed_html(
page:octavo.pages.Page
):
The article HTML of page for feed readers, with absolute link and image addresses
feed_html renders a page's article for feed readers, without the title block, contents or copy buttons. It turns every link and image address into an absolute URL by joining the address the site uses to the page's public URL. Each item's description holds this HTML as escaped XML text. Feed readers display it as HTML. A page with no article text keeps its own description. Authors become dc:creator elements and categories become category elements, as in Quarto's feeds.
Site.rss_feed
def rss_feed(
page:octavo.pages.Page
):
RSS 2.0 feed XML for a listing page, or '' if the site has no site-url
The channel holds the feed's title, link, description and optional language, and an atom:link to the feed's own URL.
RSS feeds always put the newest posts first, independently of listing order. Here, order: 0 puts First Blog Post first in the default listing, but the newer post comes first in the feed.
Feed text is XML-escaped. Publication dates use GMT. Date-only values mean midnight UTC; timestamps without a timezone also use UTC. Timestamps with an offset are converted to the equivalent time in GMT.
feed_idx = Page('blog/index.md', '---\ntitle: My Blog Title\nlisting:\n contents: posts\n feed: true\n---\n')
test_eq(test_site.listing_pages(feed_idx), [p_post1, p_post2])
rss = test_site.rss_feed(feed_idx)
test_eq(rss, test_site.rss_feed(p_blog_idx))
RSS escapes title and description text, including ampersands and angle brackets. The newest post appears first.
special_idx = Page('blog/index.md', '---\ntitle: My Blog Title & Updates\nlisting:\n contents: posts\n---\n')
special_post = Page('blog/posts/third-post&example.md', '---\ntitle: Third Blog Post & Example\ndescription: Example <description> & text\nauthor: {name: Author Four & Author Five, url: "https://example.com/team?a=1&b=2"}\ndate: 2022-11-07T10:30:00+02:00\n---\n')
feed_site = Site([special_idx, p_post1, p_post2, special_post], site_url='https://example.com')
channel = ET.fromstring(feed_site.rss_feed(special_idx)).find('channel')
test_eq(channel.findtext('title'), 'My Blog Title & Updates')
test_eq(channel.findtext('description'), 'My Blog Title & Updates')
items = channel.findall('item')
test_eq([o.findtext('title') for o in items], ['Third Blog Post & Example', 'Second Blog Post', 'First Blog Post'])
test_eq(items[0].findtext('description'), 'Example <description> & text')
Each author gets a dc:creator element holding a plain name, whether the frontmatter gives a string, a dictionary or a mixed list. Item links and GUIDs share the public URL.
def creators(item): return [o.text for o in item.findall('{http://purl.org/dc/elements/1.1/}creator')]
test_eq(creators(items[0]), ['Author Four & Author Five'])
test_eq(creators(items[1]), ['Author One', 'Author Two', 'Author Three'])
test_eq(creators(items[2]), ['Author Two', 'Author One'])
test_eq(items[0].findtext('link'), 'https://example.com/blog/posts/third-post&example.html')
test_eq(items[0].findtext('guid'), items[0].findtext('link'))
Date-only values use midnight UTC. An explicit timezone offset is converted to the same UTC instant.
dates = [parsedate_to_datetime(o.findtext('pubDate')) for o in items]
test_eq(dates[0], datetime.fromisoformat('2022-11-07T10:30:00+02:00'))
test_eq(dates[1], datetime(2022, 8, 25, tzinfo=timezone.utc))
test_eq(dates[2], datetime(2022, 7, 28, tzinfo=timezone.utc))
[(o.findtext('title'), o.findtext('pubDate')) for o in items]
[('Third Blog Post & Example', 'Mon, 07 Nov 2022 08:30:00 GMT'),
('Second Blog Post', 'Thu, 25 Aug 2022 00:00:00 GMT'),
('First Blog Post', 'Thu, 28 Jul 2022 00:00:00 GMT')]
By default, each item carries the page's whole article. The newest post's image becomes an absolute URL under site-url. The title block and copy buttons stay out, and the channel takes the site's title:
blog = ET.fromstring(test_site.rss_feed(p_blog_idx)).find('channel')
test_eq(blog.findtext('title'), 'TestSite')
article = blog.find('item').findtext('description')
assert 'src="https://example.com/blog/posts/second-post/cover%20image.gif"' in article
assert 'title-block' not in article and 'vm-copy' not in article
article
Links between pages, including same-page anchors, also become absolute, because a feed reader shows the article away from the site. Here, the feed keeps the two newest pages, takes its own title, and gives partial items. The second post has a description; the tricky post has none, so its item falls back to the first paragraph:
tricky = Page('blog/posts/tricky.md', '---\ntitle: Tricky\ndate: 2022-08-01\n---\nSee [the first post](first-post/index.md) and [usage](#usage).\n\nMore text.\n')
short_idx = Page('blog/index.md', '---\ntitle: My Blog Title\nlisting:\n contents: posts\n feed:\n items: 2\n type: partial\n title: Latest\n---\n')
short = ET.fromstring(Site([short_idx, p_post1, p_post2, tricky], site_url='https://example.com').rss_feed(short_idx)).find('channel')
test_eq(short.findtext('title'), 'Latest')
test_eq([o.findtext('title') for o in short.findall('item')], ['Second Blog Post', 'Tricky'])
second,para = [o.findtext('description') for o in short.findall('item')]
test_eq(second, 'Second post [description] with `code` | example')
test_eq(para, '<p>See <a href="https://example.com/blog/posts/first-post/index.html">the first post</a> and <a href="https://example.com/blog/posts/tricky.html#usage">usage</a>.</p>')
para
Unlinked drafts
Set draft: true in a page's frontmatter and draft-mode: unlinked in octavo.yml to publish the page without advertising it. Its HTML, Markdown copy, and aliases remain accessible by URL. Listings, category counts, feeds, navigation, sitemap, and site search omit it.
Drafts are public to anyone with their URL. Marking a page as a draft does not disable code execution. Links written inside page content remain unchanged.
Draft status applies only to the page that declares it. Setting draft: true on a directory index does not mark its descendants as drafts. There is no Draft banner, and preview uses the same publication settings as a build.
This example site contains the existing blog index, one published post, and a draft under development:
p_draft = Page('blog/posts/draft/index.md', r'''---
title: Draft Post
draft: true
sidebar: true
categories: [unpublished]
aliases: [/draft-post]
---
Draft article text.
''')
draft_site = Site([p_blog_idx, p_post1, p_draft], draft_mode='unlinked', site_url='https://example.com')
test_eq(draft_site.listing_pages(p_blog_idx), [p_post1])
{'all': draft_site.pages.attrgot('title'), 'discoverable': draft_site.discoverable_pages.attrgot('title')}
{'all': ['My Blog Title', 'First Blog Post', 'Draft Post'],
'discoverable': ['My Blog Title', 'First Blog Post']}
test_eq(test_site.listing_href(p_post1), '../../index.html')
assert 'href="../../index.html#category=release"' in str(md2doc(p_post1.text).header(test_site.listing_href(p_post1)))
test_eq(draft_site.listing_href(p_draft), None)
test_eq(test_site.listing_href(p_blog_idx), None)
The listing, category counts, RSS feed, and sitemap use the same discoverable pages. The draft's sidebar: true does not override its draft status.
assert 'Draft Post' not in draft_site.render_listing(p_blog_idx)
cat_s = str(draft_site.categories_nav(p_blog_idx))
assert 'unpublished' not in cat_s and 'All (1)' in cat_s
test_eq([o.findtext('title') for o in ET.fromstring(draft_site.rss_feed(p_blog_idx)).findall('./channel/item')],
['First Blog Post'])
assert p_draft.dest not in draft_site.sitemap()
assert 'Draft Post' not in str(draft_site.navigation(p_draft))
test_eq(draft_site.linker(p_post1)('../draft/index.md'), '../draft/index.html')
draft_site.categories_nav(p_blog_idx)
'<nav class="categories-nav" aria-label="Filter by category"><ul><li><a href="#category=" aria-current="true">All (1)</a></li>\n<li><a href="#category=Example%20Category">Example Category (1)</a></li>\n<li><a href="#category=release">release (1)</a></li></ul></nav>'
Navigation omits local links to drafts, including aliases. A group remains if it contains published links, even when its own link targets a draft. In this example, Posts keeps its published child, while the draft-only group disappears. External URLs are not filtered.
draft_links = [dict(text='Posts', href=p_draft.dest, children=[dict(text='Published', href=p_post1.dest)]),
dict(text='Drafts', children=[dict(text='Draft', href='/draft-post.html#notes')]),
dict(text='Elsewhere', href='https://other.example/blog/posts/draft/index.html')]
visible = draft_site.visible_links(draft_links)
test_eq(visible, [dict(text='Posts', children=[dict(text='Published', href=p_post1.dest)]), draft_links[2]])
test_eq(draft_links[0]['href'], p_draft.dest)
draft_nav_site = Site(draft_site.pages, **draft_site.settings, nav_links=draft_links, sidebar_links=draft_links)
assert 'Drafts' not in str(draft_nav_site.header(p_post1))
assert 'Drafts' not in str(draft_nav_site.navigation(p_draft))
visible
[{'text': 'Posts',
'children': [{'text': 'Published',
'href': 'blog/posts/first-post/index.html'}]},
{'text': 'Elsewhere',
'href': 'https://other.example/blog/posts/draft/index.html'}]
Without draft-mode: unlinked, pages marked draft: true remain discoverable. Other mode values, including gone and visible, raise an error rather than silently using unlinked behavior.
test_eq(Site([p_draft]).discoverable(p_draft), True)
for mode in ['gone', 'visible']:
with expect_fail(ValueError, contains='Only draft-mode: unlinked'): Site([p_draft], draft_mode=mode)
Page metadata
Search engines show a page's <meta name="description"> under its link. Chat apps and social sites build link previews from Open Graph tags (og:) and Twitter card tags (twitter:). A page's description frontmatter gives its description tag. Two settings in octavo.yml add the preview tags, as Quarto's open-graph and twitter-card do:
description: Python supercharged for fastai development
open-graph: true
twitter-card:
creator: "@jeremyphoward"
site: "@fastdotai"
image: https://docs.fast.ai/images/layered.png
true turns a service on with its defaults. A mapping turns it on and overrides them. Both services take title, description, image, image-alt, image-width and image-height. Open Graph also takes site-name and locale, and Twitter takes card-style, creator and site.
The title defaults to the page's browser title, and the description to the page's description, else the site's. Open Graph's site-name defaults to the site title. Twitter's card-style is summary_large_image when there is an image, else summary. image is a full URL, or a path from the source root; previews need absolute URLs, so a path needs site-url. A page's own image frontmatter replaces the site's image in its previews. Descriptions lose their Markdown formatting.
A page can also set open-graph or twitter-card in its frontmatter. Its settings override the site's one by one, and turn the service on for that page.
Each service prefers its page-level image, then the page's general image, then its site-level image. With none configured, it uses the body-image fallback from page_image. A top-level image in octavo.yml, like Quarto's website.image, is the last resort for pages that have none of these, such as a listing page with no image of its own. Like the services' site-level images, it is a full URL or a path from the source root. It applies only to social previews, not to listing cards. Relative paths require site-url; without a usable image, no image tag is emitted.
Site.meta_tags
def meta_tags(
page:octavo.pages.Page, # Page whose `<head>` the tags go in
title:str, # The page's browser title
):
Description, Open Graph and Twitter card <meta> tags for page
guide.md uses its own description and first body image for Open Graph. faq.md uses the site's description. Twitter keeps its configured site image and alt text for both pages.
social = Site([Page('guide.md', '---\ntitle: Guide\ndescription: How to *start*\n---\n'), Page('faq.md', '# FAQ\n')],
title='demo', description='A demo site', open_graph=True,
twitter_card=dict(site='@demo', image='https://example.com/card.png', image_alt='A card'))
guide,faq = social.by_path['guide'],social.by_path['faq']
gtags,ftags = [str(t) for t in social.meta_tags(guide, 'Guide - demo')],[str(t) for t in social.meta_tags(faq, 'FAQ - demo')]
assert '<meta name="description" content="How to start">' in gtags
assert '<meta property="og:description" content="A demo site">' in ftags
assert not any('name="description"' in t for t in ftags)
assert '<meta name="twitter:card" content="summary_large_image">' in gtags
assert '<meta name="twitter:image:alt" content="A card">' in gtags
assert '<meta property="og:image" content="https://example.com/body.png">' in gtags
assert '<meta name="twitter:image" content="https://example.com/card.png">' in gtags
L(gtags)
['<meta name="description" content="How to start">', '<meta property="og:title" content="Guide - demo">', '<meta property="og:description" content="How to start">', '<meta property="og:image" content="https://example.com/body.png">', '<meta property="og:site_name" content="demo">', '<meta name="twitter:title" content="Guide - demo">', '<meta name="twitter:description" content="How to start">', '<meta name="twitter:image" content="https://example.com/card.png">', '<meta name="twitter:image:alt" content="A card">', '<meta name="twitter:site" content="@demo">', '<meta name="twitter:card" content="summary_large_image">']
posts/launch.md sets its own image, a path relative to the post, as for listing cards. Its previews show that image as an absolute URL built from site-url, with the page's image-alt. The site's alt text described the site's image, so it is not used. Without site-url the path cannot become a URL, and the page falls back to the site's image:
launch = Page('posts/launch.md', '---\ntitle: Launch\nimage: cover.png\nimage-alt: The launch party\n---\n')
cards = Site([launch], title='demo', site_url='https://example.com/demo/', open_graph=True,
twitter_card=dict(image='https://example.com/card.png', image_alt='A card'))
ltags = [str(t) for t in cards.meta_tags(launch, 'Launch - demo')]
assert '<meta property="og:image" content="https://example.com/demo/posts/cover.png">' in ltags
assert '<meta name="twitter:image:alt" content="The launch party">' in ltags
nourl = Site([launch], title='demo', twitter_card=dict(image='https://example.com/card.png'))
assert '<meta name="twitter:image" content="https://example.com/card.png">' in [str(t) for t in nourl.meta_tags(launch, 'Launch - demo')]
L(ltags)
['<meta property="og:title" content="Launch - demo">', '<meta property="og:image" content="https://example.com/demo/posts/cover.png">', '<meta property="og:image:alt" content="The launch party">', '<meta property="og:site_name" content="demo">', '<meta name="twitter:title" content="Launch - demo">', '<meta name="twitter:image" content="https://example.com/demo/posts/cover.png">', '<meta name="twitter:image:alt" content="The launch party">', '<meta name="twitter:card" content="summary_large_image">']
posts/recap.md sets its own Twitter card. Its title and card-style replace the site's, and the site's site handle still applies. Its open-graph: true turns Open Graph on for this page only:
recap = Page('posts/recap.md', '---\ntitle: Recap\nopen-graph: true\ntwitter-card:\n title: The year in review\n card-style: summary\n---\n')
rtags = [str(t) for t in Site([recap], title='demo', twitter_card=dict(site='@demo')).meta_tags(recap, 'Recap - demo')]
assert '<meta name="twitter:title" content="The year in review">' in rtags
assert '<meta name="twitter:card" content="summary">' in rtags
assert '<meta name="twitter:site" content="@demo">' in rtags
assert '<meta property="og:title" content="Recap - demo">' in rtags
L(rtags)
['<meta property="og:title" content="Recap - demo">', '<meta property="og:site_name" content="demo">', '<meta name="twitter:title" content="The year in review">', '<meta name="twitter:site" content="@demo">', '<meta name="twitter:card" content="summary">']
A top-level image gives previews to pages with no image of their own. The blog's index, blog/index.md, has no body image, so its previews use the site's image, a path from the source root. The post keeps its body image, and a service's own site-level image still takes precedence over the top-level one:
home_site = Site([Page('blog/index.md', '---\ntitle: Blog\nlisting: {}\n---\n'), Page('blog/post.md', '# Post\n')],
title='demo', site_url='https://example.com/demo/', image='images/home.png', open_graph=True, twitter_card=True)
blog_idx,blog_post = home_site.by_path['blog/index'],home_site.by_path['blog/post']
htags = [str(t) for t in home_site.meta_tags(blog_idx, 'Blog - demo')]
for t in ['<meta property="og:image" content="https://example.com/demo/images/home.png">',
'<meta name="twitter:image" content="https://example.com/demo/images/home.png">',
'<meta name="twitter:card" content="summary_large_image">']: assert t in htags
assert '<meta property="og:image" content="https://example.com/demo/blog/body.png">' in [str(t) for t in home_site.meta_tags(blog_post, 'Post - demo')]
own_card = Site(home_site.pages, **home_site.settings | dict(twitter_card=dict(image='card.png')))
assert '<meta name="twitter:image" content="https://example.com/demo/card.png">' in [str(t) for t in own_card.meta_tags(blog_idx, 'Blog')]
L(htags)
Supported settings
Octavo reads only the settings listed here: SITE_KEYS from octavo.yml, PAGE_KEYS from frontmatter, and BLOCK_KEYS from the blocks nested under some of those keys. The names use underscores, as snake_keys returns them. unknown_keys lists the settings Octavo ignores, so that build can warn about site settings it doesn't recognise, and a tool that converts another site to Octavo can report what won't carry over.
unknown_keys
def unknown_keys(
settings:dict, # Settings with underscore keys, as `snake_keys` returns them
keys:set, # `SITE_KEYS` or `PAGE_KEYS`
):
Keys in settings that Octavo doesn't read, with those inside a block as block.key
This site misspells toc-depth. The blog page asks for Quarto's code-fold for the whole page, and its listing for Quarto's sort menu; Octavo has neither:
test_eq(unknown_keys(snake_keys({'title': 'demo', 'toc-dept': 2}), SITE_KEYS), ['toc_dept'])
blog = snake_keys({'title': 'Blog', 'code-fold': True, 'listing': {'sort': 'date desc', 'sort-ui': True}})
test_eq(unknown_keys(blog, PAGE_KEYS), ['code_fold', 'listing.sort_ui'])
Building the site
build writes each page as HTML and GitHub-flavored Markdown. Listings are appended in memory before rendering; source files remain unchanged.
Set css to add stylesheets after the built-in styles, and js to add module scripts after Octavo's own (see head_tags). Pass head for additional HTML in every page’s <head>.
Pagefind indexes the rendered <main> content and writes search files under pagefind/. A search-indexing failure raises an exception.
Pass out or configure output to choose the destination. The build deletes the existing output directory before writing. Do not point it at a directory containing files you need to keep.
The return value maps HTML page paths to unresolved document links. build also warns about site settings that Octavo doesn't read, as listed by unknown_keys.
resolve_output
def resolve_output(
root, output
):
Resolve an output directory that neither contains nor sits inside the sources
resolve_output resolves an explicit output path from the working directory and rejects overlap with the sources in either direction. Output cannot equal, contain, or sit inside the source directory, including through symlinks. YAML output is resolved relative to octavo.yml by read_cfg. Site captures its source root and output setting as absolute paths when created. The CLI validates before loading executable pages; Site.build validates again before deleting output.
with tempfile.TemporaryDirectory() as d:
source = Path(d).resolve()/'docs'
source.mkdir()
(source/'octavo.yml').write_text('output: ../_site')
with working_directory(source.parent):
loaded = Site.from_dir('docs')
test_eq(loaded.root, source)
test_eq(loaded.settings.output, source.parent/'_site')
test_eq(resolve_output(source, '_preview'), source.parent/'_preview')
with working_directory(source):
test_eq(read_cfg('.')['output'], loaded.settings.output)
test_eq(resolve_output(source, '../_preview'), source.parent/'_preview')
test_eq(resolve_output(None, '../_preview'), source.parent/'_preview')
test_eq(resolve_output(source, loaded.settings.output), source.parent/'_site')
with expect_fail(ValueError, contains='Set output'): resolve_output(source, None)
Site.build
def build(
out:str=None, # Output directory relative to cwd; defaults to the site's output setting
head:tuple=(), # Extra chunks inserted verbatim into every page's `head`
):
Write every page as HTML and GFM, with the redirects, generated files, assets, and sitemap
A build rejects its source directory, every ancestor, and every descendant, including paths reached through symlinks. This applies to hidden output directories such as _site too. Rejection happens before deleting anything; source files and existing output remain intact.
Explicit build(out=...) and from_dir(output=...) arguments select destinations relative to the working directory, not the source directory.
with tempfile.TemporaryDirectory() as d:
source = Path(d)/'project/docs'
source.mkdir(parents=True)
marker = source/'index.md'
marker.write_text('# Keep this source')
alias = Path(d)/'source-link'
alias.symlink_to(source, target_is_directory=True)
nested = source/'public'
nested.mkdir()
saved = nested/'keep.txt'
saved.write_text('Keep existing output too')
for dest in (source.parent, source, alias, nested, alias/'public', source/'_site'):
with expect_fail(ValueError, contains='sources'): resolve_output(source, dest)
with expect_fail(ValueError, contains='sources'): Site([], root=source).build(dest)
test_eq(marker.read_text(), '# Keep this source')
test_eq(saved.read_text(), 'Keep existing output too')
with working_directory(source.parent):
test_eq(Site.from_dir('docs').build('preview'), {})
assert (source.parent/'preview/index.html').exists()
test_eq(Site.from_dir('docs', output='override').build(), {})
assert (source.parent/'override/index.html').exists()
test_eq(marker.read_text(), '# Keep this source')
Let's build our test site. Its toc-depth: 2 counts the page title as the first level, so the config page's table of contents lists its ## section but not the ### one:
out = built.settings.output
test_eq(built.build(), {}) # no unresolved links
assert not (out/'drafts').exists()
html = (out/'api/config.html').read_text()
assert '<link rel="icon" href="../favicon.png">' in html
toc = html[html.index('class="page-side"'):html.index('<main')]
assert 'Reading' in toc and 'Search order' not in toc
assert '<pagefind-modal-trigger compact>' in html
search_files = L((out/'pagefind').iterdir()).attrgot('name')
for nm in ['pagefind.js','pagefind-component-ui.js','pagefind-component-ui.css']: assert nm in search_files
{'pages': len(list(out.rglob('*.html'))), 'search_files': len(search_files)}
{'pages': 3, 'search_files': 14}
The homepage links to api/config.html in HTML and api/config.md in Markdown. The old configuration.html URL redirects to api/config.html.
assert 'href="api/config.html"' in (out/'index.html').read_text()
md = (out/'index.md').read_text()
assert '(api/config.md)' in md and '01_config' not in md
assert 'url=api/config.html' in (out/'configuration.html').read_text()
print(md)
---
title: Home
---
A\_name starts with [config](api/config.md).
```python
items = ["a_b"]
```
$\displaystyle x_1 + y_2$
Build the earlier blog example with social previews enabled. Its index precedes the posts and has no body image; generated cards and the footer must not become its social image. The second post's inferred thumbnail keeps its encoded filename in both HTML and Markdown.
previews = Site(test_site.pages, **test_site.settings, open_graph=True, twitter_card=True, footer='<img src="footer.png">')
with tempfile.TemporaryDirectory() as d:
previews.build(d)
index_html = (Path(d)/p_blog_idx.dest).read_text()
index_md = (Path(d)/p_blog_idx.dest).with_suffix('.md').read_text()
post_html = (Path(d)/p_post2.dest).read_text()
assert 'src="posts/second-post/cover%20image.gif"' in index_html
assert '(posts/second-post/cover%20image.gif)' in index_md
The post's social previews use the same image as its listing card, resolved against the site's public URL.
url = 'https://example.com/blog/posts/second-post/cover%20image.gif'
for service in ['og', 'twitter']:
assert f'{service}:image" content="{url}"' in post_html
assert f'{service}:image"' not in index_html
url
'https://example.com/blog/posts/second-post/cover%20image.gif'
A site created without root copies no source assets. This example also contains a link to old.md, which is absent from the page list and appears in the build’s missing-link report.
stray = Page('stray.md', '---\ntitle: Stray\n---\n\nSee [the old page](old.md).\n')
loose = Site(list(built.pages)+[stray], title='nbdev')
with tempfile.TemporaryDirectory() as d: loose_broken = loose.build(d)
loose_broken
{'stray.html': ['old.md']}
A directory _metadata.yml supplies inherited DEFAULTS for pages below it (useful when a directory cannot hold an index.md), and highlight plugs a custom (text, lang) -> inner_html | None highlighter into Site.build.
with tempfile.TemporaryDirectory() as d:
src = Path(d)/'src'
(src/'glyphs').mkdir(parents=True)
(src/'glyphs/_metadata.yml').write_text('toc: false\n')
(src/'glyphs/add.md').write_text('# Add\n\n## Details\n\n```bpl\n1+2\n```\n')
(src/'glyphs/override.md').write_text('---\ntoc: true\n---\n# Override\n\n## Details\n')
s = Site.from_dir(src, highlight={'bpl': [(r'\d+', 'hl-number')]})
pages_by_nm = {p.nm: p for p in s.pages}
test_eq(s.opts(pages_by_nm['add']).toc, False)
test_eq(s.opts(pages_by_nm['override']).toc, True)
test_eq(s.build(Path(d)/'out'), {})
add_html = (Path(d)/'out/glyphs/add.html').read_text()
assert 'data-lang="bpl"' in add_html and '<span class="hl-number">1</span>+<span class="hl-number">2</span>' in add_html
assert 'On this page' not in add_html
Unlinked drafts still build to HTML and Markdown, and their aliases still redirect. Pagefind indexes only the blog index and published post. The count below comes from Pagefind reading the rendered files, not from Octavo's page list.
with tempfile.TemporaryDirectory() as d:
draft_out = Path(d)/'site'
test_eq(draft_site.build(draft_out), {})
for ext in ['.html', '.md']: assert 'Draft article text.' in (draft_out/Path(p_draft.dest).with_suffix(ext)).read_text()
assert p_draft.dest in (draft_out/'draft-post.html').read_text()
blog = (draft_out/p_blog_idx.dest).read_text()
side,main = blog[blog.index('class="page-side"'):blog.index('<main')], blog[blog.index('<main'):]
assert '<summary>Categories</summary>' in side and 'release (1)' in side and 'unpublished' not in side
assert 'On this page' not in blog and 'categories-nav' not in main
indexed = loads((draft_out/'pagefind/pagefind-entry.json').read_text())
searchable = sum(o['page_count'] for o in indexed['languages'].values())
test_eq(searchable, 2)
{'rendered_pages': len(draft_site.pages), 'searchable_pages': searchable}
{'rendered_pages': 3, 'searchable_pages': 2}
Generated files
Pass GeneratedFile objects in files to include text produced in memory. The build writes each file verbatim and excludes its source path from copied assets. Destinations that collide with pages, copied assets, or other generated files raise ValueError.
(root/'images/circles.svg.py').write_text('print("<svg/>")\n')
svg = GeneratedFile('images/circles.svg.py', 'images/circles.svg', '<svg/>\n')
gen_site = Site(list(built.pages), root=root, files=[svg], **built.settings)
test_eq(gen_site.build(), {})
test_eq((out/'images/circles.svg').read_text(), '<svg/>\n')
test_eq((out/'images/circles.svg.py').exists(), False)
# fail on duplicate file
with expect_fail(ValueError): Site(list(built.pages), root=root, files=[svg, svg], **built.settings).build()
# fail on conflict with page
with expect_fail(ValueError): Site(list(built.pages), root=root, files=[GeneratedFile('x/y.py', 'api/config.html', 'z')], **built.settings).build()
# fail on conflict with source asset
with expect_fail(ValueError): Site(list(built.pages), root=root, files=[GeneratedFile('x/y.py', 'images/logo.svg', 'z')], **built.settings).build()
L(str(o.relative_to(out)) for o in sorted(out.rglob('*')) if o.is_file())
['_octavo/octavo.css', '_octavo/octavo.js', 'api/config.html', 'api/config.md', 'configuration.html', 'index.html', 'index.md']
Site styles
Site-wide and page-level css paths are relative to the site source root, without a leading /. Set css: styles.css in octavo.yml or page frontmatter to load the root's styles.css. Octavo adjusts the emitted link for each output page: posts/first.html loads ../styles.css.
A light theme can change the header and prose colors without changing the grid:
:root {
color-scheme: light;
--hue: 215;
--oct-header-bg: #eee;
--oct-header-fg: #444;
--oct-primary: #2670b7;
--font: system-ui, sans-serif;
--text: 17px;
--color-text: #333;
--color-background: #fff;
--color-accent: #2670b7;
}
To use another font, load its stylesheet or define @font-face, then set font-family. Verify that the font loaded in the browser. Merely naming it does not load it. Compare the homepage and a nested article at desktop and phone widths before changing content widths or category placement.
Custom layout
Use page-layout: custom, as in Quarto, for a page that needs its own layout, such as a landing page. Set it in that page’s frontmatter:
page-layout: custom
css: index.css
js: index.js
pagetitle: Welcome to my project
The page keeps the site header and its navigation, but uses a full-width content area without the sidebar, generated title block, table of contents, or “View as Markdown” link. It also omits the default article typography (prose styling), so you can style the content yourself. A markdown version is still generated.
css adds a stylesheet for this page, loaded after the site-wide stylesheets. Here, index.css is a path relative to the site root. Later styles can override earlier rules of equal specificity.
js adds a module script for this page, loaded after the site-wide scripts. Its path is also relative to the site root.
pagetitle sets the browser tab title without changing the page’s title in navigation or listings. These settings are independent: you can use css, js and pagetitle on standard pages too.
home = Page('index.md', '---\ntitle: Home\npagetitle: Home page\npage-layout: custom\ncss: index.css\njs: index.js\n---\n\n# Welcome\n')
custom = Site(list(built.pages)+[home], root=root, **built.settings, css='styles.css', js='site.js')
test_eq(custom.opts(home).page_layout, 'custom')
test_eq(custom.build(), {})
htm = (out/'index.html').read_text()
assert '<header class="site-header">' in htm and '<title>Home page</title>' in htm
assert '<main class="custom">' in htm and '<main prose>' not in htm
assert 'title-block' not in htm and 'class="page-side"' not in htm
assert '<details class="site-nav" open>' not in htm
assert 'View as Markdown' not in htm
assert 'styles.css' in htm and 'index.css' in htm and htm.index('styles.css') < htm.index('index.css')
assert htm.index('src="site.js"') < htm.index('src="index.js"')
plain = (out/'api/config.html').read_text()
assert 'title-block' in plain and '<main prose>' in plain
side,main = plain[plain.index('<aside class="page-side">'):plain.index('<main')], plain[plain.index('<main'):]
assert '<div class="page-actions">' in side and 'View as Markdown' in side and 'View as Markdown' not in main
assert 'href="config.md">View as Markdown</a>' in plain
assert plain.count('href="../styles.css"') == 1