mkdocs:使用自定义 python 模块来补充插件

mkdocs: Using a custom python module to complement a plugin

我想为 mkdocs 编写一个插件,允许添加自定义 python 代码文件。 这是一个 example of plugin.

我想将该模块放在网站的主目录中,与 mkdocs.yml 文件一起,并在其中声明该模块,例如:

python_module=mycode.py

然后我会在插件的代码中使用,比如:

from mkdocs.plugins import BasePlugin

from jinja2 import Template
import importlib

class MarkdownExtraDataPlugin(BasePlugin):
    "Execute piece of code"

    def on_page_markdown(self, markdown, page, config, site_navigation, **kwargs):

        python_module = config.get('python_module')

        if python_module:
            # Add path, here is the question:
            python_module = os.path.join(*?????*, python_module)

            # do import here:
            importlib.import_module(python_module)

        ....
        return result

我现在遇到的问题是我不知道模块的代码如何知道 yaml 文件的位置,或者 markdown 文件的位置。有没有可能,那会是 config 词典的一部分吗?

更新

我写了插件和made it available on github。非常感谢您的帮助。

答案取决于您使用的 MkDocs 版本。在 #1376 the path was added to the config object as the attribute config.config_file_path. However, that won't be available until the next release (1.0). Regardless, earlier versions include an undocumented config option config['config_file_path'] 中保存文件的位置。但是要小心,因为任何未记录的功能如有更改,恕不另行通知。

关于Markdown文件的位置,可以在various attributes of the page object passed to the plugin event. You have your pick of page.input_path, page.output_path, page.abs_input_path, and page.abs_output_path. Again, these are undocumented and subject to change in a future release without notice. In fact, #1504建议改为page.file.src_pathpage.file.dest_pathpage.file.abs_src_pathpage.file.abs_dest_path ] 对于 1.0 版本。但这是针对 pre-1.0 软件工作的风险。随着开发人员试图把它做好,事情会发生变化。好消息是 1.0 版本将在未来锁定这些东西。

完全披露:我是 MkDocs 开发团队的成员。