0

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

我想将模块放在网站的主目录中,在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字典的一部分吗?

更新

我编写了插件并在 github 上提供了它。非常感谢你的帮助。

4

1 回答 1

1

The answer depends on which version of MkDocs you are using. In #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'] which holds the location of the file. Be careful however, as any undocumented features are subject to change without notice.

As for the location of the Markdown file, that is available in 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 proposes changing them to page.file.src_path, page.file.dest_path, page.file.abs_src_path, and page.file.abs_dest_path for the 1.0 release. But that's the risk in working against pre-1.0 software. Things change as the developers try to get it right. The good news is that the 1.0 release will lock these things down going forward.

Full disclosure: I am a member of the MkDocs development team.

于 2018-06-25T01:30:31.963 回答