mdx-include
mdx-include is a Python Markdown extension that enables the inclusion of local or remote files directly into Markdown documents. It provides advanced features like recursive includes, file content slicing by line/column, caching of included files, and detection of circular inclusions. The current stable version is 1.4.2, with the last update released in July 2022, indicating an irregular release cadence.
Common errors
-
CircularIncludeException: Circular inclusion detected: A.md -> B.md -> C.md -> A.md
cause By default, `mdx-include` prevents infinite loops by raising an error when it detects a file including itself directly or indirectly.fixConfigure the `mdx_include` extension with `allow_circular_inclusion: True` to change this behavior, allowing the affected file to be included non-recursively. For example: `extensions=['mdx_include', {'mdx_include': {'allow_circular_inclusion': True}}]` -
AttributeError: 'IncludeExtension' object has no attribute 'configs'
cause Attempting to access configuration with an outdated or incorrect API, or passing configuration in an incompatible format.fixEnsure you are passing configurations as a dictionary when initializing the extension, e.g., `extensions=[{'mdx_include': {'base_path': 'docs'}}]. The `configs` attribute itself is not directly exposed for external manipulation after initialization.
Warnings
- gotcha The default include syntax `{! file_path_or_url !}` can conflict with other Python Markdown extensions (e.g., `markdown.extensions.attr_list`).
- gotcha Circular inclusions (e.g., File A includes B, B includes C, C includes A) raise a `CircularIncludeException` by default.
- breaking Do not use `mdx-include` concurrently with the `markdown-include` extension.
- gotcha The inline `recurs_state` option (`{!+ file!}`) to force recursion is only effective if the global `recursion` configuration option is set to `None`. If `recursion` is `False`, the inline override will not work.
Install
-
pip install mdx-include
Imports
- mdx_include
from mdx_include import IncludeExtension
import markdown html = markdown.markdown(text, extensions=['mdx_include'])
Quickstart
import markdown
import os
# Create a dummy file to include
with open('include_me.md', 'w') as f:
f.write('This content is from an included file.\n\n- Item 1\n- Item 2')
# Markdown content that includes the dummy file
markdown_content = """
# Main Document
This is the main content.
{! include_me.md !}
End of document.
"""
html = markdown.markdown(
markdown_content,
extensions=['mdx_include']
)
print(html)
# Clean up dummy file
os.remove('include_me.md')