diff --git a/content/nested/index.md b/content/nested/index.md index e20b4ad..0d61f29 100644 --- a/content/nested/index.md +++ b/content/nested/index.md @@ -1 +1,6 @@ +--- +tags: + - tag1 + - tag2 +--- # Nested diff --git a/content/tags/tag1.md b/content/tags/tag1.md new file mode 100644 index 0000000..58be046 --- /dev/null +++ b/content/tags/tag1.md @@ -0,0 +1 @@ +Tag 1 content diff --git a/hooks/tags.py b/hooks/tags.py new file mode 100644 index 0000000..966014e --- /dev/null +++ b/hooks/tags.py @@ -0,0 +1,54 @@ +from mkdocs.utils import meta +from mkdocs.structure.files import File, Files +import tempfile +import os +import shutil + +TAGS_TEMP_DIR = os.path.join(tempfile.gettempdir(), "tags") + +shutil.rmtree(TAGS_TEMP_DIR, ignore_errors=True) +os.mkdir(TAGS_TEMP_DIR) + +def on_files(files: Files, config): + tags = set() + + template = config["theme"].get_env().get_template("tag-template.md") + list_template = config["theme"].get_env().get_template("tag-list-template.md") + + for file in files.documentation_pages(): + with open(file.abs_src_path) as f: + _, metadata = meta.get_data(f.read()) + tags.update(metadata.get("tags", [])) + + for tag in tags: + found_tag_page = files.get_file_from_path(f"tags/{tag}.md") + + if found_tag_page: + with open(found_tag_page.abs_src_path) as f: + content, _ = meta.get_data(f.read()) + else: + content = "" + + + filename = f"{tag}.md" + with open(os.path.join(TAGS_TEMP_DIR, filename), "w") as f: + f.write(template.render(tag=tag, content=content)) + + files.append(File( + path=filename, + src_dir=TAGS_TEMP_DIR, + dest_dir=os.path.join(config["site_dir"], "tags"), + use_directory_urls=True + )) + + with open(os.path.join(TAGS_TEMP_DIR, "tags.md"), "w") as f: + f.write(list_template.render()) + + files.append(File( + path="tags.md", + src_dir=TAGS_TEMP_DIR, + dest_dir=config["site_dir"], + use_directory_urls=True + )) + + return files diff --git a/mkdocs.yml b/mkdocs.yml index dda4cf7..1782718 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -8,3 +8,4 @@ theme: hooks: - hooks/nav.py + - hooks/tags.py diff --git a/theme/tag-list-template.md b/theme/tag-list-template.md new file mode 100644 index 0000000..a2a692e --- /dev/null +++ b/theme/tag-list-template.md @@ -0,0 +1,6 @@ +--- +template: tag.html +title: All tags +--- + +All the tags diff --git a/theme/tag-template.md b/theme/tag-template.md new file mode 100644 index 0000000..ae04974 --- /dev/null +++ b/theme/tag-template.md @@ -0,0 +1,6 @@ +--- +template: tag.html +title: {{ tag }} +--- + +{{ content }} diff --git a/theme/tag.html b/theme/tag.html new file mode 100644 index 0000000..e308577 --- /dev/null +++ b/theme/tag.html @@ -0,0 +1,5 @@ +I'm a tag + +{{ page.title }} + +{{ page.content }}