From 2ef0ceec89a1823faff48f366974c8d3d6708161 Mon Sep 17 00:00:00 2001 From: Joan Puigcerver Date: Thu, 6 Feb 2025 09:36:40 +0100 Subject: [PATCH] include page icons --- alias/plugin.py | 18 +++++++++++------- test_plugin.py | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/alias/plugin.py b/alias/plugin.py index f82c947..46e9bc4 100644 --- a/alias/plugin.py +++ b/alias/plugin.py @@ -50,14 +50,17 @@ def find_anchor_by_id(anchors: list[MarkdownAnchor], anchor_id: str) -> Markdown return None -def get_page_title(page_src: str, meta_data: dict): +def get_page_title(page_src: str, meta_data: dict, include_icon: bool = False): """Returns the title of the page. The title in the meta data section will take precedence over the H1 markdown title if both are provided.""" - return ( - meta_data['title'] - if 'title' in meta_data and isinstance(meta_data['title'], str) - else get_markdown_title(page_src) - ) + if 'title' in meta_data and isinstance(meta_data['title'], str): + title = meta_data['title'] + if include_icon and 'icon' in meta_data and isinstance(meta_data['icon'], str): + icon = ':' + meta_data['icon'].replace('/', '-') + ':' + title = f'{icon} {title}' + else: + title = get_markdown_title(page_src) + return title def get_alias_names(meta_data: dict): @@ -140,6 +143,7 @@ class AliasPlugin(BasePlugin): config_scheme = ( ('verbose', config_options.Type(bool, default=False)), ('use_anchor_titles', config_options.Type(bool, default=False)), + ('use_page_icon', config_options.Type(bool, default=False)), ) aliases = {} log = logging.getLogger(f'mkdocs.plugins.{__name__}') @@ -211,7 +215,7 @@ def on_files(self, files: Files, /, **_): meta_data['alias']['text'] # if meta_data['alias'] is a dictionary and 'text' is a key if isinstance(meta_data['alias'], dict) and 'text' in meta_data['alias'] - else get_page_title(source, meta_data) + else get_page_title(source, meta_data, self.config['use_page_icon']) ), 'url': file.src_uri, 'anchors': anchors, diff --git a/test_plugin.py b/test_plugin.py index 0431ba1..c188f20 100644 --- a/test_plugin.py +++ b/test_plugin.py @@ -38,6 +38,20 @@ def test_get_page_title_4(): assert get_page_title(source, meta) == 'The actual title' +def test_get_page_title_5(): + """Test page with both meta title and icon enabled""" + source = "# Not the title\n\nsome text\n" + meta = {'title': 'The actual title', 'icon': 'path/to/my-icon'} + assert get_page_title(source, meta, include_icon=True) == ':path-to-my-icon: The actual title' + + +def test_get_page_title_6(): + """Test page with both meta title and icon but disabled""" + source = "# Not the title\n\nsome text\n" + meta = {'title': 'The actual title', 'icon': 'path/to/my-icon'} + assert get_page_title(source, meta, include_icon=False) == 'The actual title' + + def test_get_alias_name_1(): """Test alias from meta extraction""" meta = {'alias': 'my-alias'}