Skip to content

Updating Navigation

Overview

This article provides instructions on using a Python script to automatically update the navigation section in your mkdocs.yml file based on the directory structure of your documentation. The script will exclude any IMAGES folders and their contents from the navigation.

Prerequisites

  • Python installed on your computer.
  • Your documentation files are organized in a directory (e.g., docs).
  • Your mkdocs.yml file is located in the same directory as this script.

Script Description

The provided Python script scans the docs directory, generates a navigation structure, and updates the mkdocs.yml file accordingly.

Script: update_mkdocs_nav.py

Save the following script as update_mkdocs_nav.py in the same directory as your mkdocs.yml file:

import os
import yaml

def generate_nav_structure(base_path, exclude_folders=["IMAGES"]):
    nav_structure = []

    for root, dirs, files in os.walk(base_path):
        # Remove excluded folders from directories list
        dirs[:] = [d for d in dirs if d not in exclude_folders]

        # Generate the relative path for the root directory
        rel_path = os.path.relpath(root, base_path)
        if rel_path == '.':
            rel_path = ''

        # Collect markdown files in the current directory
        markdown_files = [f for f in files if f.endswith('.md')]

        if not rel_path:  # If we are at the base path
            for file in markdown_files:
                nav_structure.append({file.replace('.md', ''): os.path.join(rel_path, file).replace('\\', '/')})
        else:
            sub_nav = []
            for file in markdown_files:
                sub_nav.append({file.replace('.md', ''): os.path.join(rel_path, file).replace('\\', '/')})
            if sub_nav:
                nav_structure.append({rel_path.replace('\\', '/'): sub_nav})

    return nav_structure

def update_mkdocs_yaml(nav_structure, mkdocs_path):
    with open(mkdocs_path, 'r') as f:
        mkdocs_config = yaml.safe_load(f)

    mkdocs_config['nav'] = nav_structure

    with open(mkdocs_path, 'w') as f:
        yaml.dump(mkdocs_config, f, sort_keys=False)

if __name__ == "__main__":
    # Assuming the script is in the same directory as mkdocs.yml
    script_dir = os.path.dirname(os.path.realpath(__file__))
    base_path = os.path.join(script_dir, "docs")
    mkdocs_path = os.path.join(script_dir, "mkdocs.yml")

    nav_structure = generate_nav_structure(base_path)
    update_mkdocs_yaml(nav_structure, mkdocs_path)

    print("mkdocs.yml has been updated with the new navigation structure.")

Usage Instructions

Running the Script

  1. Open a terminal or command prompt.
  2. Navigate to the directory containing your mkdocs.yml file and the update_mkdocs_nav.py script.
  3. Run the script using Python:
    python update_mkdocs_nav.py
    

Expected Output

The script will scan the docs directory, generate a navigation structure, and update the mkdocs.yml file. You should see a message indicating that the mkdocs.yml file has been updated.

Modifying the Script for a Different Computer

If you need to run this script on a different computer or in a different directory setup, follow these steps:

  1. Open the update_mkdocs_nav.py script in a text editor.
  2. Locate the following lines:
    base_path = os.path.join(script_dir, "docs")
    mkdocs_path = os.path.join(script_dir, "mkdocs.yml")
    
  3. Modify these lines to reflect the paths on your new setup. For example:
    base_path = "D:/Projects/Documentation/docs"
    mkdocs_path = "D:/Projects/Documentation/mkdocs.yml"
    
  4. Save the changes and run the script as described in the usage instructions.

Troubleshooting

  • Python not found: Ensure Python is installed and added to your system's PATH.
  • File not found errors: Verify the paths to docs and mkdocs.yml are correct.
  • YAML errors: Ensure the mkdocs.yml file is valid YAML before running the script.

Conclusion

By using this script, you can automate the process of updating the navigation structure in your mkdocs.yml file, ensuring it always reflects the current state of your documentation files. This helps maintain an organized and up-to-date knowledge base with minimal manual effort.