在Sphinx中结合MyST使用替换(substitution)功能是否可行?
Can MyST Markdown be combined with Sphinx substitution features?
Absolutely! MyST Markdown plays nicely with Sphinx's substitution features—this is actually a big part of why it's such a great fit for maintaining scalable, consistent documentation. Let me break down the main ways to combine them:
1. Use Sphinx's native reStructuredText substitutions
MyST fully supports Sphinx's classic substitution syntax (the |variable| format). Here's how to set it up:
- Global substitutions via
conf.py: Define reusable substitutions across all your docs by adding torst_prolog:rst_prolog = """ .. |project_name| replace:: My Awesome Documentation .. |current_version| replace:: v1.2.3 """ - Per-document substitutions: You can also define substitutions directly in a MyST Markdown file using reStructuredText syntax:
.. |author_name| replace:: Jane Doe
Once defined, just drop the substitution tag anywhere in your Markdown content, like:
Welcome to |project_name| (version |current_version|), written by |author_name|!
2. MyST's native substitution extension (Jinja2-style)
For a more Markdown-friendly approach, MyST has its own substitution extension that uses Jinja2-like {{ variable }} syntax. Here's how to use it:
- Enable the extension in
conf.py:myst_enable_extensions = ["substitution"] - Define variables in document frontmatter: Add custom variables directly at the top of your MyST file:
--- project: My Awesome Docs version: v1.2.3 --- This is the documentation for {{ project }}, version {{ version }}. - Global MyST substitutions: Set site-wide variables in
conf.pyusingmyst_substitutions:
Then use them anywhere:myst_substitutions = { "company": "My Tech Company", "copyright_year": "2024" }© {{ copyright_year }} {{ company }}
Key notes
- These two approaches (Sphinx's
|variable|and MyST's{{ variable }}) are independent—they won't conflict with each other, so you can use whichever fits your workflow better. - Document-level variables (from frontmatter) will override global
myst_substitutionsif there's a name clash, giving you flexibility per page.
内容的提问来源于stack exchange,提问作者M. Toya
相关产品推荐
相关产品推荐

