I would like to write a plugin for mkdocs that allows to add a file of custom python code. Here is an example of plugin.
I would like to put the module in the website's main dir, alongside the mkdocs.yml
file, and declare that module in there, e.g.:
python_module=mycode.py
Then I would use in the code of the plugin, something like:
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
The problem I am having at this point is I don't know how the code of the module could know the location of the yaml file, or the location of the markdown file. By any chance, would that be part of the config
dictionary?
I wrote the plugin and made it available on github. Thanks a lot for your help.
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.