You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在reStructuredText的include指令中传递参数替换占位符?

Passing Parameters to Included reStructuredText Files

Great question! Passing dynamic parameters to included reStructuredText files isn't a built-in feature of the core include directive, but there are several practical workarounds that fit different use cases:

1. Use Docutils Substitutions (No Extra Tools Needed)

This is the simplest approach if you're working with plain docutils, no extensions required. It leverages docutils' built-in substitution system to replace placeholders in your included file.

Steps:

  • Update planet.rst to use a substitution reference instead of a hardcoded placeholder:
    Hello |planet|.
    
  • In each target RST file, define the substitution before including planet.rst:
    # For Earth-specific file
    .. |planet| replace:: Earth
    .. include:: planet.rst
    
    # For Mars-specific file
    .. |planet| replace:: Mars
    .. include:: planet.rst
    

When docutils processes the file, it will replace |planet| in the included content with the value you defined, resulting in Hello Earth. or Hello Mars. as needed.

Pros/Cons:

  • ✅ No external dependencies or scripts
  • ❌ Less scalable if you have multiple variables or complex logic

2. Use Sphinx + Jinja2 Templates (For Sphinx-Based Projects)

If you're using Sphinx to build your documentation, you can leverage Jinja2 templating to pass parameters to included files. This requires the sphinxcontrib-jinja2 extension.

Steps:

  1. Install the extension:
    pip install sphinxcontrib-jinja2
    
  2. Add it to your conf.py extensions list:
    extensions = [
        # ... your other extensions
        'sphinxcontrib.jinja2'
    ]
    
  3. Rename planet.rst to planet.j2 (Jinja2 template file) and update the placeholder:
    Hello {{ planet }}.
    
  4. In your target RST files, use the jinja directive to include the template and pass parameters:
    .. jinja::
       :file: planet.j2
       :context:
          planet: Saturn
    

Sphinx will render the template with the provided context, replacing {{ planet }} with your specified value during the build process.

Pros/Cons:

  • ✅ Highly flexible for complex variables or logic
  • ✅ Integrates seamlessly with Sphinx workflows
  • ❌ Requires Sphinx and an additional extension

3. Custom Preprocessing Script (Full Flexibility)

If you need complete control over parameter passing, write a simple preprocessing script to replace placeholders in planet.rst before including it. This works for both plain docutils and Sphinx projects.

Example Python Script:

import re
import os

def process_rst_files():
    # Read the base planet content
    with open("planet.rst", "r") as f:
        planet_template = f.read()

    # Iterate over all RST files except planet.rst
    for filename in os.listdir("."):
        if not filename.endswith(".rst") or filename == "planet.rst":
            continue

        with open(filename, "r") as f:
            content = f.read()

        # Find include directives with planet parameter
        pattern = r".. include:: planet.rst :planet: (\w+)"
        matches = re.findall(pattern, content)
        if matches:
            planet_name = matches[0]
            # Replace placeholder in the template
            rendered_content = planet_template.replace("<planet>", planet_name)
            # Replace the include directive with rendered content
            updated_content = re.sub(pattern, rendered_content, content)
            # Write back to a processed file (or overwrite the original)
            output_filename = filename.replace(".rst", "_processed.rst")
            with open(output_filename, "w") as f:
                f.write(updated_content)

if __name__ == "__main__":
    process_rst_files()

Usage:

  • In your target RST files, write the include directive with a parameter:
    .. include:: planet.rst :planet: Mars
    
  • Run the script to generate processed RST files, then use those files with docutils/Sphinx.

Pros/Cons:

  • ✅ Unlimited flexibility for custom logic
  • ✅ Works with any docutils-based toolchain
  • ❌ Requires maintaining a custom script
  • ❌ Adds an extra step to your build process

内容的提问来源于stack exchange,提问作者Thomas Rademacher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:44:18