Skip to content

Commit 50c080c

Browse files
authored
Expose page.content_title property for plugin authors (#52)
Add a public content_title property to the Page class that exposes the previously private _title_from_render attribute. This gives plugin authors access to the heading text extracted from the first <h1> tag in the page content, with HTML tags stripped and entities unescaped, without reaching into private API. Fixes mkdocs/mkdocs#3532
1 parent 2caeffe commit 50c080c

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

mkdocs/structure/pages.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,19 @@ def __repr__(self):
9696
meta: MutableMapping[str, Any]
9797
"""A mapping of the metadata included at the top of the markdown page."""
9898

99+
@property
100+
def content_title(self) -> str | None:
101+
"""
102+
The title of the page extracted from the first `<h1>` heading in the page content.
103+
104+
This is `None` until the page has been rendered. Unlike `title`,
105+
this does not fall back to any other source — it reflects exactly
106+
the `<h1>` text from the rendered Markdown, with HTML tags stripped
107+
and entities unescaped. It is useful for plugins that need the raw
108+
heading text as it appears in the page body.
109+
"""
110+
return self._title_from_render
111+
99112
@property
100113
def url(self) -> str:
101114
"""The URL of the page relative to the MkDocs `site_dir`."""

mkdocs/tests/structure/page_tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,17 @@ def test_page_title_from_markdown(self):
329329
self.assertEqual(pg.title, "Welcome to MkDocs")
330330
pg.render(cfg, Files([fl]))
331331
self.assertEqual(pg.title, "Welcome to MkDocs")
332+
self.assertEqual(pg.content_title, "Welcome to MkDocs")
333+
334+
def test_content_title_property(self):
335+
"""content_title is None before rendering, set after."""
336+
cfg = load_config()
337+
fl = File("testing.md", cfg.docs_dir, cfg.site_dir, cfg.use_directory_urls)
338+
pg = Page(None, fl, cfg)
339+
pg.read_source(cfg)
340+
self.assertIsNone(pg.content_title)
341+
pg.render(cfg, Files([fl]))
342+
self.assertEqual(pg.content_title, "Welcome to MkDocs")
332343

333344
def _test_extract_title(self, content, expected, extensions={}):
334345
md = markdown.Markdown(

0 commit comments

Comments
 (0)