mkdocs / mkdocs-redirects

Open source plugin for Mkdocs page redirects
MIT License
176 stars 25 forks source link

Add support for hash fragments #16

Closed squidfunk closed 2 years ago

squidfunk commented 4 years ago

First of all: this is a very useful plugin, thanks for writing it!

I'm currently in the process of rewriting the docs for Material for MkDocs in https://github.com/squidfunk/mkdocs-material/pull/1735 and, as the overall structure changed a lot, want to redirect some of the pages. However, some pages were merged.

Idea

Allow hash fragments in URL mappings, so that the redirect will jump to the subsection of the page, e.g.:

plugins:
  - search
  - redirects:
      redirect_maps:
        releases/4.md: upgrading.md#upgrading-to-4-x
        releases/5.md: upgrading.md#upgrading-to-5-x
        releases/changelog.md: changelog.md

Actual behavior

When building the site, the plugin prints:

WARNING -  Redirect target 'upgrading.md#upgrading-to-4-x' does not exist! 
WARNING -  Redirect target 'upgrading.md#upgrading-to-5-x' does not exist! 

Desired behavior

No error, redirects work.

pawamoy commented 3 years ago

This can be achieved with mkdocs-gen-files instead.

# mkdocs.yml
plugins:
- search
- gen-files:
    scripts:
    - redirects.py
# docs/redirects.py
import mkdocs_gen_files

redirect_map = {
    "guides/package.md": "../../guide/actions",
    "guides/webservice.md": "../../guide/actions",
    "guides/update.md": "../../guide/actions/#updating-a-project",
    "guides/ides.md": "../../guide/environment/#ide-text-editor",
}

redirect_template = """
<script type="text/javascript">
    window.location.href = "{link}";
</script>
<a href="{link}">Redirecting...</a>
"""

for page, link in redirect_map.items():
    with mkdocs_gen_files.open(page, "w") as fd:
        print(redirect_template.format(link=link), file=fd)

Note however that you must use relative links with this solution, not file names. And mkdcs-gen-files is Python 3.7+.