Giter Club home page Giter Club logo

mkdocs-macros-plugin's Introduction

Mkdocs-Macros

Unleash the power of MkDocs with variables and macros

License: MIT Language PyPI Github macros

📂 Used by > 2K repositories on Github
🥇 Listed as High-Quality Plugin

mkdocs-macros-plugin is a general-purpose plugin for MkDocs
that uses variables and macros (functions) to automate tasks, and produce richer and more beautiful pages.

The unit price of product A is {{ unit_price }} EUR.
Taking the standard discount into account,
the sale price of 50 units is {{ price(unit_price, 50) }} EUR.

View the mkdocs-macro documentation on Read the Docs.

Overview

mkdocs-macros-plugin is a plugin that makes it easier for contributors of an MkDocs website to produce richer and more beautiful pages. It transforms the markdown pages into jinja2 templates that use variables, calls to macros and custom filters.

You can also partially replace MkDocs plugins with mkdocs-macros modules, and pluglets (pre-installed modules).

Using variables

You can leverage the power of Python in markdown thanks to jinja2 by writing this :

The unit price of product A is {{ unit_price }} EUR.
Taking the standard discount into account,
the sale price of 50 units is {{ price(unit_price, 50) }} EUR.

If you defined a price() function, this could translate into:

The unit price of product A is 10.00 EUR.
Taking the standard discount into account,
the sale price of 50 units is 450.00 EUR.

The result of a macro can be HTML code: this makes macros especially useful to make custom extensions to the syntax of markdown, such as buttons, calls to email, embedding YouTube videos, etc.

It is possible to use the wide range of facilities provided by Jinja2 templates such as conditions ({% if ... %}) and loops ({% for ... %}).

Defining variables

Regular variables can be defined in five ways:

No Validity For whom Description
1. global designer of the website in the mkdocs.yml file, under the extra heading
2. global contributor in external yaml definition files
3. global programmer in a main.py file (Python), by adding them to a dictionary
4. local (page) writer in the YAML header of each Markdown page
5. local (page) writer with a {%set variable = value %} statement

In addition, predefined objects are provided (local and global), typically for the environment, project, page, git information, etc.

Macros and filters

Similarly programmers can define their own macros and filters, as Python functions in the main.py file, which the users will then be able to use without much difficulty, as jinja2 directives in the markdown page.

Installation

Prerequisites

  • Python version > 3.7
  • MkDocs version >= 1.0 (compatible with post 1.5 versions)

Standard installation

pip install mkdocs-macros-plugin

"Manual installation"

To install the package, download it and run:

pip install .
# or...
python setup.py install

Development/test installation

To install the extra dependencies required for testing the package, run:

pip install "mkdocs-macros-plugin[test]"

Declaration of plugin

Declare the plugin in the file mkdocs.yml:

plugins:
    - search
    - macros

Note: If you have no plugins entry in your config file yet, you should also add the search plugin. If no plugins entry is set, MkDocs enables search by default; but if you use it, then you have to declare it explicitly.

By default, undefined variables are printed to the page as-is. If you wish for a page to fail on undefined variables, you should use the below configuration instead:

plugins:
    - search
    - macros
          on_undefined: strict

For details and more options, see the documentation.

Check that it works

The recommended way to check that the plugin works properly is to add the following command in one of the pages of your site (let's say info.md):

{{ macros_info() }}

In the terminal, restart the environment:

> mkdocs serve

You will notice that additional information now appears in the terminal:

INFO    -  Building documentation...
[macros] Macros arguments: {'module_name': 'main', 'include_yaml': [], 'j2_block_start_string': '', 'j2_block_end_string': '', 'j2_variable_start_string': '', 'j2_variable_end_string': ''}

Within the browser (e.g. http://127.0.0.1:8000/info), you should see a description of the plugin's environment:

macros_info()

If you see it that information, you should be all set.

Give a good look at the General List, since it gives you an overview of what you can do out of the box with the macros plugin.

The other parts give you more detailed information.

Using pluglets

What are pluglets?

Pluglets are small, easy-to-write programs that use mkdocs-macro's foundation to offer services to mkdocs projects, which would normally be offered by plugins.

Pluglets are Python packages, which can be hosted on github, and distributed through PyPI.

How to add a pluglet to an mkdocs project?

Install it:

pip install <pluglet_name>

Declare it in the project's config (mkdocs.yml) file:

plugins:
  - search
  - macros:
      modules:
        - <pluglet_name> 

How to write a pluglet?

See instructions in the documentation.

A sample pluglet can be found in mkdocs-test (github).

List of existing pluglets

See the wiki page on Github.

mkdocs-macros-plugin's People

Contributors

2dkot avatar akhmerov avatar alxgu avatar anatoly-scherbakov avatar andre601 avatar bomberus avatar caomingpei avatar crispydrone avatar eyllanesc avatar fergven avatar flynneva avatar fralau avatar garfieldnate avatar honzajavorek avatar ijmitch avatar jannismain avatar jbesomi avatar jc-l avatar jimporter avatar jsoucheiron avatar kchr avatar marcospereira avatar mlenkeit avatar mriedem avatar oleg-nenashev avatar sebastienwarin avatar sgilson avatar simonmarquis avatar timozerrer avatar timvink avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

mkdocs-macros-plugin's Issues

Incompatible with mkdocs 1.1

I recently noticed failed builds:

Mkdocs cleaned up their sources, the string_type attribute is no longer in the util module.

following code was removed

PY3 = sys.version_info[0] == 3

if PY3:                         # pragma: no cover
    string_types = str,         # noqa
    text_type = str             # noqa
else:                           # pragma: no cover
    string_types = basestring,  # noqa
    text_type = unicode         # noqa

log = logging.getLogger(__name__)

#23

Don't require mkdocs-material in setup.py?

This is a pretty minor issue, but setup.py requires mkdocs>=0.17 and mkdocs-material. The latter requires mkdocs>=1.1, so if you try to install a pre-1.1 version of mkdocs along with mkdocs-macros-plugin, you'll get a non-fatal error from pip that mkdocs is incompatible:

ERROR: mkdocs-material 6.1.6 has requirement mkdocs>=1.1, but you'll have mkdocs 1.0.4 which is incompatible.

It looks like mkdocs-material is only required in this package for the tests, so it doesn't actually need to be installed for all users. I think the Pythonic way of listing dev/test dependencies is with a requirements.txt file; an alternative would be extra_requires in setup.py:

...
extras_require={
    'test': ['mkdocs-material'],
},
...

Then people who want to test this package could call pip install 'mkdocs-macros-plugin[test]'.

Assuming this makes sense, I'm happy to make a PR for this or for anyone else to do so. I'm not picky. :)

macros plugin interprets syntax in code blocks as macro tags - fails to build

I have a markdown document where I am detailing syntax.

In particular, I am using the description: {% Vimeo ID}

With the mkdocs_macro_plugin enabled, this syntax which is contained in a code block fails to build.
I believe that the plugin is trying to interpret the {% as a tag.

Would it be possible to exclude the macro plugin parsing the contents of code blocks?

The build error is:

INFO - [macros] - ERROR # Macro Rendering Error

TemplateSyntaxError: Encountered unknown tag 'Vimeo'.

Traceback (most recent call last):
  File "/home/deploy/.local/lib/python3.7/site-packages/mkdocs_macros/plugin.py", line 441, in render
    md_template = self.env.from_string(markdown)
  File "/home/deploy/.local/lib/python3.7/site-packages/jinja2/environment.py", line 941, in from_string
    return cls.from_code(self, self.compile(source), globals, None)
  File "/home/deploy/.local/lib/python3.7/site-packages/jinja2/environment.py", line 638, in compile
    self.handle_exception(source=source_hint)
  File "/home/deploy/.local/lib/python3.7/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/home/deploy/.local/lib/python3.7/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<unknown>", line 3, in template
jinja2.exceptions.TemplateSyntaxError: Encountered unknown tag 'Vimeo'.

Plugin fails to load if Git is not in PATH

This may be limited to Windows, I don't have a linux setup to test with at the moment. All I was getting was this weird error message "[WinError 2] The system cannot find the file specified". Hacked up the plugin source to add some except blocks to try to trace it back to the root cause and:

Traceback (most recent call last):
  File "c:\users\sesa249423\appdata\local\programs\python\python38\lib\site-packages\macros\plugin.py", line 313, in on_config
    define_env(self)
  File "c:\users\sesa249423\appdata\local\programs\python\python38\lib\site-packages\macros\context.py", line 239, in define_env
    env.variables['git'] = get_git_info()
  File "c:\users\sesa249423\appdata\local\programs\python\python38\lib\site-packages\macros\context.py", line 147, in get_git_info
    r[var] = subprocess.check_output(command,
...
FileNotFoundError: [WinError 2] The system cannot find the file specified

Hacking up the source more, I was able to simple change the except clause to omit the exception type so it catches any exceptions, now it works fine.

Reference variables defined in mkdocs.yml directly inside macro

This is probably not an issue so much as a question from a very junior programmer. How do you reference variables defined in the mkdocs.yml directly inside macro code without passing them in as a parameter? I can define a variable inside mkdocs.yml under 'extra', reference it in the template, and pass it in as a parameter in the macro function, but I'd rather just directly reference that variable in the macro code rather than pass it in. I tried a bunch of ways to do this but couldn't get the context...

Thanks much! Your macro plugin is awesome and just the thing I needed for what we wanted to do with our docs.

Help with git revision date macro

How could I create macro {{git_revision}} that would get replaced by the git revision of that file which it is part of.

I wanted to do it as a part of the module but not sure how to get a path to the markdown file.

Build fails after upgrade on December 7th.

After the upgrade, we can build sites using your plugin, see the error below (extract from jenkins):

�[32m[macros] Macros arguments:�[0m {'module_name': 'main', 'include_yaml': []}
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/macros/plugin.py", line 214, in _load_module
module = importlib.import_module(python_module)
File "/usr/local/lib/python3.7/importlib/init.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1006, in _gcd_import
File "", line 983, in _find_and_load
File "", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'main'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/bin/mkdocs", line 8, in
sys.exit(cli())
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 764, in call
return self.main(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 717, in main
rv = self.invoke(ctx)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 1137, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/local/lib/python3.7/site-packages/click/core.py", line 555, in invoke
return callback(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/mkdocs/main.py", line 163, in build_command
), dirty=not clean)
File "/usr/local/lib/python3.7/site-packages/mkdocs/commands/build.py", line 240, in build
config = config['plugins'].run_event('config', config)
File "/usr/local/lib/python3.7/site-packages/mkdocs/plugins.py", line 94, in run_event
result = method(item, **kwargs)
File "/usr/local/lib/python3.7/site-packages/macros/plugin.py", line 261, in on_config
self._load_module()
File "/usr/local/lib/python3.7/site-packages/macros/plugin.py", line 234, in _load_module
(python_module, self.project_dir))
ImportError: Macro plugin could not find custom 'main' module in '/home/ubuntu/workspace/et_previous_version_macro_plugin'.

Note; we reverted back to the previous version and worked.

Syntax highlight with Pigments

Thanks for this plugin! I am using it with the macro code_from_file mentioned in this issue and the Material theme, but I can't make them work together with syntax highlight, the file is shown, but without any colors. The source code differs when using the macro:

<pre><code class="xxx">mycode

But when using direct code blocks, it generates HTML like this:

<div class="codehilite"><pre><span></span><span class="p">{</span>

Any idea how to solve this?

`git.tag` is crashing when no tags are present

Quoted from pull request #38 by @kalanzun.

Diagnosis Information

The except clauses actually return None, because dict().update() returns None.

The pull request changes get_git_info() to actually return the diagnosis information in r. The except clauses now just updates r with r.update({}) and at the very end of the function, get_git_info() returns r.

git repositories without tags

If the git repository has no tags, git describe --tags fails with error code 128 and aborts git_get_config(). However, the other commands still provide useful information.

This pull request adds a try except block around the git call and ignores error 128 for r['tag']. The function continues to collect information for git repositories without tags.

Configurable YAML data file

Hi @fralau, I love your macros plugin and use it almost every day! ❤️

Feature request incoming though. 😜

Feature Request

I would like the ability to configure the macros plugin with YAML data files to initialize the env.variables dictionary with.

Example mkdocs.yml

###########
# Plugins #
###########
plugins:
  # Macros
  - macros:
      data:
        - 'data/authors.yaml'  # A YAML file containing information about authors.
        - 'data/projects.yaml' # A YAML file containing information about projects.

My expectation would be that extra from the mkdocs.yml is still initialized into the env.variables dictionary, but that any additional data files supplied would merge into env.variables, potentially overriding the values picked up from the extra property. The latest file loaded would take precedence.

Reasoning

I'm using the mdocs-macros-plugin for a pretty large documentation site.

At this point our mkdocs.yml is filled to the brim with data from the extra object of our project. This smells of an anti-pattern to me. I'd prefer, if possible, not to mix MkDocs configuration with documentation data.

I realize that I could do this myself in Python!

However, it seems to me like mixing data with configuration is really a bad practice. I'd be willing to wager that lots of people have wanted this functionality, or at least would use it if it were available, but haven't bothered to open an issue or write up a feature request.

Thanks @fralau!

ModuleNotFoundError: No module named 'main'

I'm seeing this error when installing 0.4.16:

  File "/Users/squidfunk/Desktop/mkdocs-test/venv/bin/mkdocs", line 8, in <module>
    sys.exit(cli())
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/mkdocs/__main__.py", line 152, in build_command
    build.build(config.load_config(**kwargs), dirty=not clean)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/mkdocs/commands/build.py", line 236, in build
    config = config['plugins'].run_event('config', config)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/mkdocs/plugins.py", line 94, in run_event
    result = method(item, **kwargs)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/macros/plugin.py", line 315, in on_config
    self._load_module()
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/macros/plugin.py", line 219, in _load_module
    module = import_module(self.project_dir, module_name)
  File "/Users/squidfunk/Desktop/mkdocs-test/venv/lib/python3.8/site-packages/macros/util.py", line 29, in import_module
    return importlib.import_module(module_name)
  File "/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
  File "<frozen importlib._bootstrap>", line 991, in _find_and_load
  File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'main'

How to reproduce

pip install mkdocs mkdocs-macros-plugin

mkdocs.yml:

site_name: My Docs
plugins:
  - macros

Then run:

mkdocs build

Macros get ran while in code block

While making a 'contributing' page, I have found that when I insert the macro within a markdown code block, the macro gets parsed and not nullified like everything else in the code block.

My use:
mkdocs.yml

extra:
  table:
    head: '| Application | Usage | Website | Github | Docker Hub |'
    head2: '|-|-|-|-|-|'

contribute.md

\```
{{ table.head }}
{{ table.head2 }}
\```

(backslashes added to cancel the close, they are not actually in the file)

contribute.md will actually get parsed and show

| Application | Usage | Website | Github | Docker Hub |
|-|-|-|-|-|

instead of showing {{ table.head }} and {{ table.head2 }} like I was expecting it to. I am trying to make this a copy and paste template for any new pages so I really don't want to add a character before hand to break it.

I can see how this is expected behavior but I would like it to stay unparsed within the code block in case I need to change the table in the future, I wouldn't have to go in and change the table for each file.

Access plugin's parameters

It can be useful to access the arguments in the config file, e.g.:

plugins:
  ...
  - macros:
      module_name: mymodule
      include_dir: include

As {{ plugin.module_name }} or {{ plugin.include_dir }}.

0.5.4 on pypi?

Hey, I found your plugin very helpful, thank you so much! Any plans to publish 0.5.4 on PyPI?

Version 0.3.0 now requires a main.py file

Hi, Your plugin is great and allows clean macro/template usage but I was previously using version 0.2.4 and recently upgraded to 0.3.2 to stay current. In the upgrade i noticed that i now must have a main.py file in the root or add the python_module to the mkdocs yaml.

Did i miss some configuration option or is a python module now required. I have simple macros and don't need the code based solution and would prefer not to have main.py.

Doc from here: https://github.com/fralau/mkdocs_macros_plugin#defining-variables-macros-and-filters-in-python-code

Add Changelog

Please, a changelog would be very useful for packages that depend on the mkdocs_macros_plugin. Could you add one? Thanks!

Setting for include root directory

Currently:

The root directory for your included files is in docs_dir

How about making this plugin configuration that defaults to docs_dir if not set ?

- macros:
      root_dir:  inc       <== relative to the mkdocs.yml location

Currently I need to put this in the docs folder with other files, but then those files get rendered also which is wrong as they are partials. Then I need exlusion plugin etc... This folder should be outside of docs to avoid that hessle and currently this is not possible to set.

Unable to process markdown files that contain default Jinja template markers

If this plugin tries to process a markdown template that contains default Jinja template markers, this will fail. For example, imagine a markdown file trying to explain some Ansible features. Might look something like:

The Ansible file task  works like this:

- task: "create a directory
  file:
    path: "{{ folder_path }}"
    state: directory
    recurse: true

This won't work, as the 'folder_path' variable won't be in extra. And it should not render that particular string in the first place.

Does that make sense?

Get url parameters

Is it possible to get any url parameters that might be entered? So, if my url is https://example.com/wiki_page/?code=5, can I get the 5 from the url? And url variables I've tried to find can get all the url up to the ?.

Using Jinja2 for loops

I have trouble using Jinja2 for loops in mkdocs_macros_plugin.

mkdocs.yml

plugins:
  - search
  - macros

extra:
  files:
    foo:
      name: 'Foo'
    bar:
      name: 'Bar'

index.md

{% for file in files %}
- {{ file.name }}
{% endfor %}

Expected index.html

- Foo
- Bar

Actual index.html

- 
- 

Regression: custom 'module_name' doesn't work with '__init__.py' - style modules anymore

Just upgraded from 0.4.9 and getting the error message below. It happens when the Python module that the module_name configuration value points to is an __init__.py file.

I think it has to do with the recent refactoring of the module import that happened here (but haven't had time to investigate more yet): e419062#diff-15d04a928c1fac5996433591e06a4569

Relevant config:

plugins:
- search
- macros:
   module_name: ci

Error stack:

❯ mkdocs build --site-dir public
[macros] Macros arguments: {'module_name': 'ci', 'include_dir': '', 'include_yaml': [], 'j2_block_start_string': '', 'j2_block_end_string': '', 'j2_variable_start_string': '', 'j2_variable_end_string': ''}
Traceback (most recent call last):
  File "/tmp/tingex/.direnv/python-3.8.5/bin/mkdocs", line 8, in <module>
    sys.exit(cli())
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/mkdocs/__main__.py", line 152, in build_command
    build.build(config.load_config(**kwargs), dirty=not clean)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/mkdocs/commands/build.py", line 236, in build
    config = config['plugins'].run_event('config', config)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/mkdocs/plugins.py", line 94, in run_event
    result = method(item, **kwargs)
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/macros/plugin.py", line 314, in on_config
    self._load_module()
  File "/tmp/tingex/.direnv/python-3.8.5/lib/python3.8/site-packages/macros/plugin.py", line 242, in _load_module
    raise ImportError("Macro plugin could not find custom '%s' "
ImportError: Macro plugin could not find custom 'ci' module in '/tmp/tingex'.

git required

Since updating to 0.4.4 git seems to be required. Running without git installed:

Traceback (most recent call last):
 File "/usr/local/bin/mkdocs", line 8, in <module>
   sys.exit(cli())
 File "/usr/local/lib/python3.6/site-packages/click/core.py", line 829, in __call__
   return self.main(*args, **kwargs)
 File "/usr/local/lib/python3.6/site-packages/click/core.py", line 782, in main
   rv = self.invoke(ctx)
 File "/usr/local/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
   return _process_result(sub_ctx.command.invoke(sub_ctx))
 File "/usr/local/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
   return ctx.invoke(self.callback, **ctx.params)
 File "/usr/local/lib/python3.6/site-packages/click/core.py", line 610, in invoke
   return callback(*args, **kwargs)
 File "/usr/local/lib/python3.6/site-packages/mkdocs/__main__.py", line 159, in build_command
   build.build(config.load_config(**kwargs), dirty=not clean)
 File "/usr/local/lib/python3.6/site-packages/mkdocs/commands/build.py", line 239, in build
   config = config['plugins'].run_event('config', config)
 File "/usr/local/lib/python3.6/site-packages/mkdocs/plugins.py", line 94, in run_event
   result = method(item, **kwargs)
 File "/usr/local/lib/python3.6/site-packages/macros/plugin.py", line 309, in on_config
   define_env(self)
 File "/usr/local/lib/python3.6/site-packages/macros/context.py", line 239, in define_env
   env.variables['git'] = get_git_info()
 File "/usr/local/lib/python3.6/site-packages/macros/context.py", line 148, in get_git_info
   universal_newlines=True).strip()
 File "/usr/lib64/python3.6/subprocess.py", line 356, in check_output
   **kwargs).stdout
 File "/usr/lib64/python3.6/subprocess.py", line 423, in run
   with Popen(*popenargs, **kwargs) as process:
 File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
   restore_signals, start_new_session)
 File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
   raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'git': 'git'

I could not find the requirement in the docs, and version 0.2.4 did not require git.

mkdocs_macros_plugin does not run with Python 3.6

I experienced this issue when running mkdocs build with Python 3.6.10 on travis-ci (full log). The exception is:

$ mkdocs build
[macros] Macros arguments: {'module_name': 'main', 'include_dir': '', 'include_yaml': [], 'j2_block_start_string': '', 'j2_block_end_string': '', 'j2_variable_start_string': '', 'j2_variable_end_string': ''}
Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.6.10/bin/mkdocs", line 8, in <module>
    sys.exit(cli())
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/mkdocs/__main__.py", line 159, in build_command
    build.build(config.load_config(**kwargs), dirty=not clean)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/mkdocs/commands/build.py", line 239, in build
    config = config['plugins'].run_event('config', config)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/mkdocs/plugins.py", line 94, in run_event
    result = method(item, **kwargs)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/macros/plugin.py", line 309, in on_config
    define_env(self)
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/macros/context.py", line 235, in define_env
    env.variables['git'] = get_git_info()
  File "/home/travis/virtualenv/python3.6.10/lib/python3.6/site-packages/macros/context.py", line 146, in get_git_info
    text=True).strip()
  File "/opt/python/3.6.10/lib/python3.6/subprocess.py", line 356, in check_output
    **kwargs).stdout
  File "/opt/python/3.6.10/lib/python3.6/subprocess.py", line 423, in run
    with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'text'
The command "mkdocs build" exited with 1.

According to the docs the text argument does not exist in 3.6.

I am not sure if this needs fixing, but the communicated requirements for the plugin are Python >= 3.5.

Bug in linking within the ReadTheDocs docs

Hi, just came to learn about the plugin and noticed a bug. The following link is broken:

Screenshot_2021-04-01 mkdocs-macros

I'm visualising the problem below by the diff syntax. The green is what should be in place, the red is what is there now:

+ https://mkdocs-macros-plugin.readthedocs.io/en/latest/pluglets/
- https://mkdocs-macros-plugin.readthedocs.io/en/pluglets

The markup in the source looks correct, so I don't know how to fix this. It's probably something in the settings of either MkDocs or ReadTheDocs.

Compatibility with mkdocs > 1.0 ?

In mkdocs post 1.0, the interface to on_page_markdown has been altered.

To maintain backward compatibility with the older version, we have modified so:

    def on_page_markdown(self, markdown, page, config,
                          site_navigation=None, **kwargs):
        "Provide a hook for defining functions from an external module"

        # the site_navigation argument has been made optional
        # (deleted in post 1.0 mkdocs, but maintained here
        # for backward compatibility)

This is fixed in 0.2.0. If you find any other issue, please let us know.

fix_url doesn't return url relative to root dir

Hi,

I have the following directory structure:

.
 |-docs
 | |-index.md
 | |-issues
 | | |-index.md
 |-files
 | |-bug-template.txt
 |-main.py
 |-mkdocs.yml

I used the example code to create a button:

def define_env(env):

    # import the predefined macro
    fix_url = env.variables.fix_url # make relative urls point to root

    @env.macro
    def button(label, url):
        "Add a button"
        url = fix_url(url)
        HTML = """<a class='button' href="%s">%s</a>"""
        return HTML % (url, label)

I've added the following ninja directives to the issues/index.md file:

{{ button('Download bug template', 'files/bug-template.txt') }}  

However when I investigate the html that gets generated, the href links are of the nature "../files/bug-template.txt" instead of "../../files/bug-template.txt". When I click on the button I receive a 404 response.

image

When I move the bug-template.txt file to docs/files/ then it works correctly.

Am I interpreting the documentation incorrectly?

Thanks

Support includes

When trying to use Jinja2 includes the following happens:

ERROR   -  Error reading page '***MASKED**.md': no loader for this environment specified
[E 190417 16:34:02 ioloop:909] Exception in callback <bound method LiveReloadHandler.poll_tasks of <class 'livereload.handlers.LiveReloadHandler'>>
    Traceback (most recent call last):
      File "***MASKED***\venv\lib\site-packages\tornado\ioloop.py", line 907, in _run
        return self.callback()
      File "***MASKED***\venv\lib\site-packages\livereload\handlers.py", line 66, in poll_tasks
        filepath, delay = cls.watcher.examine()
      File "***MASKED***\venv\lib\site-packages\livereload\watcher.py", line 93, in examine
        func()
      File "***MASKED***\venv\lib\site-packages\mkdocs\commands\serve.py", line 114, in builder
        build(config, live_server=live_server, dirty=dirty)
      File "***MASKED***\venv\lib\site-packages\mkdocs\commands\build.py", line 274, in build
        _populate_page(file.page, config, files, dirty)
      File "***MASKED***\venv\lib\site-packages\mkdocs\commands\build.py", line 174, in _populate_page
        'page_markdown', page.markdown, page=page, config=config, files=files
      File "***MASKED***\venv\lib\site-packages\mkdocs\plugins.py", line 94, in run_event
        result = method(item, **kwargs)
      File "***MASKED***\venv\lib\site-packages\macros\plugin.py", line 71, in on_page_markdown
        return md_template.render(**self.variables)
      File "***MASKED***\venv\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
        return original_render(self, *args, **kwargs)
      File "***MASKED***\venv\lib\site-packages\jinja2\environment.py", line 1008, in render
        return self.environment.handle_exception(exc_info, True)
      File "***MASKED***\venv\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
        reraise(exc_type, exc_value, tb)
      File "***MASKED***\venv\lib\site-packages\jinja2\_compat.py", line 37, in reraise
        raise value.with_traceback(tb)
      File "<template>", line 235, in top-level template code
    TypeError: no loader for this environment specified

The expected behavior is that the specified filename should be interpreted relative to the currently processed file and the specified file should be loaded. The resulting content should be processed as markdown.

Crashing when running in polinux/mkdocs docker

When I start a docker from the polinux/mkdocs image adding mkdocs-macros it crashes.

I start the docker like this:

docker run -ti --name mkdocs -p 8000:8000 -v ${PWD}:/mkdocs -e "LIVE_RELOAD_SUPPORT=true" -e "ADD_MODULES=mkdocs-macros-plugin" polinux/mkdocs

The mkdocs version currently used in the docker image is 1.1.0.

In the workingdir that is mounted into the container I have this:

$ tree .
.
├── docs
│   └── index.md
└── mkdocs.yml

where index.md is the default template and mkdocs.yml contains:

$ cat mkdocs.yml
site_name: Test Docs
plugins:
    - search
    - macros

The crash I see when starting the container:

[macros] Macros arguments: {'module_name': 'main', 'include_dir': '', 'include_yaml': [], 'j2_block_start_string': '', 'j2_block_end_string': '', 'j2_variable_start_string': '', 'j2_variable_end_string': ''}
fatal: not a git repository (or any parent up to mount point /)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
[macros] Found external Python module 'main' in: /mkdocs
Traceback (most recent call last):
  File "/usr/bin/mkdocs", line 8, in <module>
    sys.exit(cli())
  File "/usr/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/usr/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/usr/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
    return _process_result(sub_ctx.command.invoke(sub_ctx))
  File "/usr/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/usr/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/usr/lib/python3.8/site-packages/mkdocs/__main__.py", line 133, in serve_command
    serve.serve(
  File "/usr/lib/python3.8/site-packages/mkdocs/commands/serve.py", line 141, in serve
    config = builder()
  File "/usr/lib/python3.8/site-packages/mkdocs/commands/serve.py", line 136, in builder
    build(config, live_server=live_server, dirty=dirty)
  File "/usr/lib/python3.8/site-packages/mkdocs/commands/build.py", line 236, in build
    config = config['plugins'].run_event('config', config)
  File "/usr/lib/python3.8/site-packages/mkdocs/plugins.py", line 94, in run_event
    result = method(item, **kwargs)
  File "/usr/lib/python3.8/site-packages/macros/plugin.py", line 318, in on_config
    self._load_module()
  File "/usr/lib/python3.8/site-packages/macros/plugin.py", line 241, in _load_module
    config_file)
NameError: name 'config_file' is not defined

I don't understand why it tries to load a module from the mounted directory at /mkdocs when there is no module there.

ModuleNotFoundError: No module named 'dateutil' with 0.4.8

Commit b8bcfaf adds a new runtime dependency on dateutil but that dependency is not listed in the install_requires list in setup.py:

https://github.com/fralau/mkdocs_macros_plugin/blob/b8bcfafb59d23e734991ac03acd408a7d98ee272/setup.py#L30

Which results in a failure to build docs with that version of the plugin:

Traceback (most recent call last):

  File "/home/travis/virtualenv/python3.6.7/bin/mkdocs", line 11, in <module>

    sys.exit(cli())

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/click/core.py", line 829, in __call__

    return self.main(*args, **kwargs)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/click/core.py", line 782, in main

    rv = self.invoke(ctx)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/click/core.py", line 1259, in invoke

    return _process_result(sub_ctx.command.invoke(sub_ctx))

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/click/core.py", line 1066, in invoke

    return ctx.invoke(self.callback, **ctx.params)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/click/core.py", line 610, in invoke

    return callback(*args, **kwargs)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/__main__.py", line 159, in build_command

    build.build(config.load_config(**kwargs), dirty=not clean)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/base.py", line 197, in load_config

    errors, warnings = cfg.validate()

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/base.py", line 107, in validate

    run_failed, run_warnings = self._validate()

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/base.py", line 62, in _validate

    self[key] = config_option.validate(value)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/config_options.py", line 130, in validate

    return self.run_validation(value)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/config_options.py", line 591, in run_validation

    plgins[item] = self.load_plugin(item, cfg)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/mkdocs/config/config_options.py", line 599, in load_plugin

    Plugin = self.installed_plugins[name].load()

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2346, in load

    return self.resolve()

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/pkg_resources/__init__.py", line 2352, in resolve

    module = __import__(self.module_name, fromlist=['__name__'], level=0)

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/macros/plugin.py", line 22, in <module>

    from .context import define_env

  File "/home/travis/virtualenv/python3.6.7/lib/python3.6/site-packages/macros/context.py", line 14, in <module>

    from dateutil.parser import parse as date_parse

ModuleNotFoundError: No module named 'dateutil'

Fail the build when there are errors

Pages with errors that have side effect free code will produce un-recoverable errors on documentation pages so being able to fail the build and go back to fix the error would be very helpfull.

How to declare a variable, which can be read by the theme, too?

I've read through all the docs, but I'm still unclear about one thing and any guidance would be very appreciated. Let's say I want to dynamically declare a variable, which would be accessible in both the macros and the MkDocs' Jinja2, because I want to use it in the HTML template of the theme, too. Normally, this would be set in extras: in the YAML config, I suppose, but as it's dynamic, it cannot be. As an example, I'll choose now.

The now is available out of the box with macros, that's nice. But let's say I want to use it in headers or footers, too, in my theme. Can I use macros to (re)define it somehow so it's available even there? I tried to modify env.conf, env.variables etc., but it seems "it's too late" at that moment. If I was writing my own plugin, I'd do something like this:

import arrow

def on_env(env, config, files):
    env.globals.update(dict(
        now=arrow.utcnow(),
        handbook_release_at=arrow.get(2020, 9, 1),
    ))

Such variables would trickle down to both the theme and the pages/macros. At least I think. What would be the correct way to do this in macros, so that I don't need to introduce my own plugin? Thanks!

Usage with mkdocs-snippet-plugin

Hi,

I am trying to use this plugin together with https://github.com/mprivat/mkdocs-snippet-plugin .

When including in mkdocs.yml like this:

plugins:
  - macros:
      verbose: true
  - snippet:
      base_path: doc

the macros-plugin works, but throws

INFO    -  [macros] - ERROR # _Macro Rendering Error_

**UndefinedError**: 'snippet' is undefined

Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/mkdocs_macros/plugin.py", line 443, in render
    return md_template.render(**page_variables)
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.9/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: 'snippet' is undefined

When including it like this:

plugins:
  - snippet:
      base_path: doc
  - macros:
      verbose: true

then the macros plugin does not work at all.

Is there a way to delegate certain function calls to other plugins?

Best regards,
stiller-leser

Possible to use front-matter?

I'd really like to use page-specific front-matter. In the actual MkDocs template, this data is provided via the dictionary page.metadata. Is it possible to access this from the mkdocs_macros_plugin?

When I run mkdocs serve all I get from the plugin is:

No module found.
Variables: {}

I didn't define any extra or custom python module, but even using {% set foo='bar' %} in the page doesn't do anything.

I'm using mkdocs, version 1.0.4 and mkdocs-macros-plugin, version 0.2.4.

Thanks!

'macros_info' is undefined in overrides/partials/source-date.html

macros_info works well on pages, but if I try to add it template - is doesn't work.

mkdocs.yml

theme:
  name: 'material'
  custom_dir: overrides

plugins:
  - macros:
      verbose: true

overrides/partials/source-date.html

<div class="md-source-date">
  {{ macros_info() }}
  <small>
    {% if page.meta.git_revision_date_localized %}
      {{ label }}: {{ page.meta.git_revision_date_localized }} / 
    {% elif page.meta.revision_date %}
      {{ label }}: {{ page.meta.revision_date }}
    {% endif %}
  </small>
</div>

logs:

INFO    -  Cleaning site directory 
INFO    -  Building documentation to directory: /builds/....
DEBUG   -  Reading markdown pages. 
DEBUG   -  Reading: index.md 
DEBUG   -  Reading: summary.md 
DEBUG   -  Reading: test.md 
DEBUG   -  Copying static assets. 
DEBUG   -  Copying media file:
...
DEBUG   -  Building theme template: sitemap.xml 
DEBUG   -  Gzipping template: sitemap.xml 
DEBUG   -  Building theme template: 404.html 
DEBUG   -  Building markdown pages. 
DEBUG   -  Building page index.md 
ERROR   -  Error building page 'index.md': 'macros_info' is undefined 
Traceback (most recent call last):
 File "/usr/local/bin/mkdocs", line 8, in <module>
   sys.exit(cli())
 File "/usr/local/lib/python3.8/site-packages/click/core.py", line 829, in __call__
   return self.main(*args, **kwargs)
 File "/usr/local/lib/python3.8/site-packages/click/core.py", line 782, in main
   rv = self.invoke(ctx)
 File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
   return _process_result(sub_ctx.command.invoke(sub_ctx))
 File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
   return ctx.invoke(self.callback, **ctx.params)
 File "/usr/local/lib/python3.8/site-packages/click/core.py", line 610, in invoke
   return callback(*args, **kwargs)
 File "/usr/local/lib/python3.8/site-packages/mkdocs/__main__.py", line 152, in build_command
   build.build(config.load_config(**kwargs), dirty=not clean)
 File "/usr/local/lib/python3.8/site-packages/mkdocs/commands/build.py", line 292, in build
   _build_page(file.page, config, files, nav, env, dirty)
 File "/usr/local/lib/python3.8/site-packages/mkdocs/commands/build.py", line 210, in _build_page
   output = template.render(context)
 File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
   self.environment.handle_exception()
 File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
   reraise(*rewrite_traceback_stack(source=source))
 File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
   raise value.with_traceback(tb)
 File "/usr/local/lib/python3.8/site-packages/material/main.html", line 4, in top-level template code
   {% extends "base.html" %}
 File "/usr/local/lib/python3.8/site-packages/material/base.html", line 150, in top-level template code
   {% block content %}
 File "/usr/local/lib/python3.8/site-packages/material/base.html", line 164, in block "content"
   {% include "partials/source-date.html" %}
 File "/builds/enterprise-api/test/sl-plantuml/overrides/partials/source-date.html", line 11, in top-level template code
   {{ macros_info() }}
jinja2.exceptions.UndefinedError: 'macros_info' is undefined

What I'm doing wrong?

Config value: 'plugins'. Error: The "marcos" plugin is not installed

Hi, developers and maintainers.

I'm experiencing install problems with your extension. The complete job raw log from Gitlab is there for troubleshooting purposes.

�[0KRunning with gitlab-runner 12.3.0 (a8a019e0)
�[0;m�[0K  on docker-auto-scale ed2dce3a
�[0;msection_start:1569826284:prepare_executor
�[0K�[0KUsing Docker executor with image python:alpine ...
�[0;m�[0KPulling docker image python:alpine ...
�[0;m�[0KUsing docker image sha256:39fb803134657c9da1b63f6e8b925d9c27b7d66d772b99f5dc762efa5580ef3e for python:alpine ...
�[0;msection_end:1569826294:prepare_executor
�[0Ksection_start:1569826294:prepare_script
�[0KRunning on runner-ed2dce3a-project-14529036-concurrent-0 via runner-ed2dce3a-srm-1569826132-a5004737...
section_end:1569826297:prepare_script
�[0Ksection_start:1569826297:get_sources
�[0K�[32;1mFetching changes with git depth set to 50...�[0;m
Initialized empty Git repository in /builds/MadeByThePinsTeam-DevLabs/legal/legal.madebythepins.tk/.git/
�[32;1mCreated fresh repository.�[0;m
From https://gitlab.com/MadeByThePinsTeam-DevLabs/legal/legal.madebythepins.tk
 * [new branch]      master     -> origin/master
�[32;1mChecking out 8abf00d9 as master...�[0;m

�[32;1mSkipping Git submodules setup�[0;m
section_end:1569826299:get_sources
�[0Ksection_start:1569826299:restore_cache
�[0Ksection_end:1569826300:restore_cache
�[0Ksection_start:1569826300:download_artifacts
�[0Ksection_end:1569826302:download_artifacts
�[0Ksection_start:1569826302:build_script
�[0K�[32;1m$ pip install mkdocs�[0;m
Collecting mkdocs
  Downloading https://files.pythonhosted.org/packages/db/f9/b0179afee0db21943120ea606eb68bda1257b96420df74b775280eb5850b/mkdocs-1.0.4-py2.py3-none-any.whl (1.2MB)
Collecting Jinja2>=2.7.1 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/1d/e7/fd8b501e7a6dfe492a433deb7b9d833d39ca74916fa8bc63dd1a4947a671/Jinja2-2.10.1-py2.py3-none-any.whl (124kB)
Collecting PyYAML>=3.10 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/e3/e8/b3212641ee2718d556df0f23f78de8303f068fe29cdaa7a91018849582fe/PyYAML-5.1.2.tar.gz (265kB)
Collecting livereload>=2.5.1 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/12/4d/30cfe74402d2e962d66d35da29bf8850b0557b559ce84d09967c8ade859e/livereload-2.6.1-py2.py3-none-any.whl
Collecting Markdown>=2.3.1 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/c0/4e/fd492e91abdc2d2fcb70ef453064d980688762079397f779758e055f6575/Markdown-3.1.1-py2.py3-none-any.whl (87kB)
Collecting tornado>=5.0 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/30/78/2d2823598496127b21423baffaa186b668f73cd91887fcef78b6eade136b/tornado-6.0.3.tar.gz (482kB)
Collecting click>=3.3 (from mkdocs)
  Downloading https://files.pythonhosted.org/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl (81kB)
Collecting MarkupSafe>=0.23 (from Jinja2>=2.7.1->mkdocs)
  Downloading https://files.pythonhosted.org/packages/b9/2e/64db92e53b86efccfaea71321f597fa2e1b2bd3853d8ce658568f7a13094/MarkupSafe-1.1.1.tar.gz
Collecting six (from livereload>=2.5.1->mkdocs)
  Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Requirement already satisfied: setuptools>=36 in /usr/local/lib/python3.7/site-packages (from Markdown>=2.3.1->mkdocs) (41.2.0)
Building wheels for collected packages: PyYAML, tornado, MarkupSafe
  Building wheel for PyYAML (setup.py): started
  Building wheel for PyYAML (setup.py): finished with status 'done'
  Created wheel for PyYAML: filename=PyYAML-5.1.2-cp37-cp37m-linux_x86_64.whl size=44103 sha256=89665259870bd06fa6472954cfa54ef0b809ac872169131d724b4b8745e8f529
  Stored in directory: /root/.cache/pip/wheels/d9/45/dd/65f0b38450c47cf7e5312883deb97d065e030c5cca0a365030
  Building wheel for tornado (setup.py): started
  Building wheel for tornado (setup.py): finished with status 'done'
  Created wheel for tornado: filename=tornado-6.0.3-cp37-cp37m-linux_x86_64.whl size=410711 sha256=59e936f37c8e0adf67f63faa47c0a1685836e77c5beb84c211d7178691ec25cf
  Stored in directory: /root/.cache/pip/wheels/84/bf/40/2f6ef700f48401ca40e5e3dd7d0e3c0a90e064897b7fe5fc08
  Building wheel for MarkupSafe (setup.py): started
  Building wheel for MarkupSafe (setup.py): finished with status 'done'
  Created wheel for MarkupSafe: filename=MarkupSafe-1.1.1-cp37-none-any.whl size=12629 sha256=7a710ead273e51bdba55e7caed53ff6e00de9210fdb75eaeab796b6be52484e0
  Stored in directory: /root/.cache/pip/wheels/f2/aa/04/0edf07a1b8a5f5f1aed7580fffb69ce8972edc16a505916a77
Successfully built PyYAML tornado MarkupSafe
Installing collected packages: MarkupSafe, Jinja2, PyYAML, tornado, six, livereload, Markdown, click, mkdocs
Successfully installed Jinja2-2.10.1 Markdown-3.1.1 MarkupSafe-1.1.1 PyYAML-5.1.2 click-7.0 livereload-2.6.1 mkdocs-1.0.4 six-1.12.0 tornado-6.0.3
�[32;1m$ pip install mkdocs-material�[0;m
Collecting mkdocs-material
  Downloading https://files.pythonhosted.org/packages/5b/22/cd9acf99048b82bfe9adab00284ed632a4885f5176a06c709cf8a8296360/mkdocs_material-4.4.2-py2.py3-none-any.whl (711kB)
Collecting mkdocs-minify-plugin>=0.2 (from mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/66/fe/47e0acd1df33a289a075af252f3d7d65fb8acec425f5fac12493669c6828/mkdocs-minify-plugin-0.2.1.tar.gz
Requirement already satisfied: mkdocs>=1 in /usr/local/lib/python3.7/site-packages (from mkdocs-material) (1.0.4)
Collecting pymdown-extensions>=4.11 (from mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/87/dd/b099881058d0e1a5f80389ff4528e7e796e7ad3d5d430f36c086dde8c824/pymdown_extensions-6.1-py2.py3-none-any.whl (219kB)
Collecting Pygments>=2.2 (from mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/5c/73/1dfa428150e3ccb0fa3e68db406e5be48698f2a979ccbcec795f28f44048/Pygments-2.4.2-py2.py3-none-any.whl (883kB)
Collecting htmlmin>=0.1.4 (from mkdocs-minify-plugin>=0.2->mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/b3/e7/fcd59e12169de19f0131ff2812077f964c6b960e7c09804d30a7bf2ab461/htmlmin-0.1.12.tar.gz
Collecting jsmin>=2.2.2 (from mkdocs-minify-plugin>=0.2->mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/17/73/615d1267a82ed26cd7c124108c3c61169d8e40c36d393883eaee3a561852/jsmin-2.2.2.tar.gz
Requirement already satisfied: Jinja2>=2.7.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (2.10.1)
Requirement already satisfied: click>=3.3 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (7.0)
Requirement already satisfied: livereload>=2.5.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (2.6.1)
Requirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (5.1.2)
Requirement already satisfied: Markdown>=2.3.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (3.1.1)
Requirement already satisfied: tornado>=5.0 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1->mkdocs-material) (6.0.3)
Collecting pep562 (from pymdown-extensions>=4.11->mkdocs-material)
  Downloading https://files.pythonhosted.org/packages/f5/31/2c8475b148c8a0c8cae39300f4346068e21909d44e0659f104ce76c3a7ef/pep562-1.0-py2.py3-none-any.whl
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/site-packages (from Jinja2>=2.7.1->mkdocs>=1->mkdocs-material) (1.1.1)
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (from livereload>=2.5.1->mkdocs>=1->mkdocs-material) (1.12.0)
Requirement already satisfied: setuptools>=36 in /usr/local/lib/python3.7/site-packages (from Markdown>=2.3.1->mkdocs>=1->mkdocs-material) (41.2.0)
Building wheels for collected packages: mkdocs-minify-plugin, htmlmin, jsmin
  Building wheel for mkdocs-minify-plugin (setup.py): started
  Building wheel for mkdocs-minify-plugin (setup.py): finished with status 'done'
  Created wheel for mkdocs-minify-plugin: filename=mkdocs_minify_plugin-0.2.1-cp37-none-any.whl size=2834 sha256=889653bc76b9224f586ca92db307b9c949c17f7b316867c5a8a05683838df380
  Stored in directory: /root/.cache/pip/wheels/17/15/12/1131ebd4aa68abdd6a0b2555ec7f22e3e62430b985710aa5a9
  Building wheel for htmlmin (setup.py): started
  Building wheel for htmlmin (setup.py): finished with status 'done'
  Created wheel for htmlmin: filename=htmlmin-0.1.12-cp37-none-any.whl size=27086 sha256=a61fe863ddcb6c8af355a746991f70e9f4b308ea936e825a66c955c4b5ccd62e
  Stored in directory: /root/.cache/pip/wheels/43/07/ac/7c5a9d708d65247ac1f94066cf1db075540b85716c30255459
  Building wheel for jsmin (setup.py): started
  Building wheel for jsmin (setup.py): finished with status 'done'
  Created wheel for jsmin: filename=jsmin-2.2.2-cp37-none-any.whl size=13919 sha256=92066e7021b1142cc5c32011d53ac647532152a31edd74ab4e1565f1a9224216
  Stored in directory: /root/.cache/pip/wheels/64/f4/de/9667d84f759289edf5442220997c6d4334637a6bb2a7b90f73
Successfully built mkdocs-minify-plugin htmlmin jsmin
Installing collected packages: htmlmin, jsmin, mkdocs-minify-plugin, pep562, pymdown-extensions, Pygments, mkdocs-material
Successfully installed Pygments-2.4.2 htmlmin-0.1.12 jsmin-2.2.2 mkdocs-material-4.4.2 mkdocs-minify-plugin-0.2.1 pep562-1.0 pymdown-extensions-6.1
�[32;1m$ pip install mkdocs-redirects�[0;m
Collecting mkdocs-redirects
  Downloading https://files.pythonhosted.org/packages/d6/78/2cb84e6c1920f0cbcaa7cbca725a4463ff78c3eaa3d03d578570ebccd7b7/mkdocs-redirects-1.0.0.tar.gz
Requirement already satisfied: mkdocs>=1.0.4 in /usr/local/lib/python3.7/site-packages (from mkdocs-redirects) (1.0.4)
Requirement already satisfied: tornado>=5.0 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (6.0.3)
Requirement already satisfied: livereload>=2.5.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (2.6.1)
Requirement already satisfied: click>=3.3 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (7.0)
Requirement already satisfied: Jinja2>=2.7.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (2.10.1)
Requirement already satisfied: Markdown>=2.3.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (3.1.1)
Requirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.7/site-packages (from mkdocs>=1.0.4->mkdocs-redirects) (5.1.2)
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (from livereload>=2.5.1->mkdocs>=1.0.4->mkdocs-redirects) (1.12.0)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/site-packages (from Jinja2>=2.7.1->mkdocs>=1.0.4->mkdocs-redirects) (1.1.1)
Requirement already satisfied: setuptools>=36 in /usr/local/lib/python3.7/site-packages (from Markdown>=2.3.1->mkdocs>=1.0.4->mkdocs-redirects) (41.2.0)
Building wheels for collected packages: mkdocs-redirects
  Building wheel for mkdocs-redirects (setup.py): started
  Building wheel for mkdocs-redirects (setup.py): finished with status 'done'
  Created wheel for mkdocs-redirects: filename=mkdocs_redirects-1.0.0-cp37-none-any.whl size=5189 sha256=f7d388538705ae87c312b9500dcc70047050e89a3f83f1468d96359f978c92ea
  Stored in directory: /root/.cache/pip/wheels/89/74/a4/479222afb41415d45b89d93bd1cff6912d3e98648a5be71e79
Successfully built mkdocs-redirects
Installing collected packages: mkdocs-redirects
Successfully installed mkdocs-redirects-1.0.0
�[32;1m$ pip install mkdocs-macros-plugin�[0;m
Collecting mkdocs-macros-plugin
  Downloading https://files.pythonhosted.org/packages/c2/d0/3d75fdb990591cc810dd7c9e10d321648c3da25309da97b018bcf07a864a/mkdocs-macros-plugin-0.2.4.tar.gz
Requirement already satisfied: mkdocs>=0.17 in /usr/local/lib/python3.7/site-packages (from mkdocs-macros-plugin) (1.0.4)
Collecting repackage (from mkdocs-macros-plugin)
  Downloading https://files.pythonhosted.org/packages/ce/19/5122e8279b7dfdbacbab648116ac84751b7c603ff3569c5e32ccb75bf0e4/repackage-0.7.3.tar.gz
Requirement already satisfied: jinja2 in /usr/local/lib/python3.7/site-packages (from mkdocs-macros-plugin) (2.10.1)
Requirement already satisfied: PyYAML>=3.10 in /usr/local/lib/python3.7/site-packages (from mkdocs>=0.17->mkdocs-macros-plugin) (5.1.2)
Requirement already satisfied: Markdown>=2.3.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=0.17->mkdocs-macros-plugin) (3.1.1)
Requirement already satisfied: livereload>=2.5.1 in /usr/local/lib/python3.7/site-packages (from mkdocs>=0.17->mkdocs-macros-plugin) (2.6.1)
Requirement already satisfied: tornado>=5.0 in /usr/local/lib/python3.7/site-packages (from mkdocs>=0.17->mkdocs-macros-plugin) (6.0.3)
Requirement already satisfied: click>=3.3 in /usr/local/lib/python3.7/site-packages (from mkdocs>=0.17->mkdocs-macros-plugin) (7.0)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.7/site-packages (from jinja2->mkdocs-macros-plugin) (1.1.1)
Requirement already satisfied: setuptools>=36 in /usr/local/lib/python3.7/site-packages (from Markdown>=2.3.1->mkdocs>=0.17->mkdocs-macros-plugin) (41.2.0)
Requirement already satisfied: six in /usr/local/lib/python3.7/site-packages (from livereload>=2.5.1->mkdocs>=0.17->mkdocs-macros-plugin) (1.12.0)
Building wheels for collected packages: mkdocs-macros-plugin, repackage
  Building wheel for mkdocs-macros-plugin (setup.py): started
  Building wheel for mkdocs-macros-plugin (setup.py): finished with status 'done'
  Created wheel for mkdocs-macros-plugin: filename=mkdocs_macros_plugin-0.2.4-cp37-none-any.whl size=9461 sha256=4ed8e027e7d9750f782276ced5fbcd8f3ac75f7865efa10d08a10fdf1f8a4e17
  Stored in directory: /root/.cache/pip/wheels/1f/ab/f1/22be9517940c86c5ed9a7d73f8286c9e713ce0cfbc7ff3a3a8
  Building wheel for repackage (setup.py): started
  Building wheel for repackage (setup.py): finished with status 'done'
  Created wheel for repackage: filename=repackage-0.7.3-cp37-none-any.whl size=3301 sha256=c7c93b69e50092f8fea95d8b38ae2e3bf08c38ff13c74955a9dacd6fae454bba
  Stored in directory: /root/.cache/pip/wheels/25/6f/ed/e1b3e23cdc94df5ce155cc0d56056cf10d99d863f393d40dca
Successfully built mkdocs-macros-plugin repackage
Installing collected packages: repackage, mkdocs-macros-plugin
Successfully installed mkdocs-macros-plugin-0.2.4 repackage-0.7.3
�[32;1m$ mkdocs build�[0;m
ERROR   -  Config value: 'plugins'. Error: The "marcos" plugin is not installed 

Aborted with 1 Configuration Errors!
section_end:1569826315:build_script
�[0Ksection_start:1569826315:after_script
�[0Ksection_end:1569826318:after_script
�[0Ksection_start:1569826318:upload_artifacts_on_failure
�[0Ksection_end:1569826319:upload_artifacts_on_failure
�[0K�[31;1mERROR: Job failed: exit code 1
�[0;m

My repository was hosted on GitLab and that was named
Legalese Website by the Pins
. How should I need to fix this?

Regards,

Andrei Jiroh

Options for custom jinja comment tag markers

Hi,

In my docs there are lots of {# .. }. Jinja treats them as invalid comments and fails. Is it possible to provide options for custom comment tag markers, in addition to existing j2_block... and j2_variable... options?

Install

Had to update setup.py to use repackage==0.6, otherwise it wouldn't install.
btw, really great plugin, thanks!

Adding graphics files to the docs directory

I'm attempting to use mkdocs in conjunction with my module's test suite to ensure that all of my documented examples function correctly.

My certain unittest.TestCase methods generate plot files that I would like to embed in my documentation.

My intended procedure for building documentation is:

  1. run my unit tests
  2. assuming they all pass, build my documentation

My macros are below. They function as expected, copying the plot file into the docs structure and returning the appropriate markdown.

The problem is, it seems that the macro is running too late and mkdocs does not see the image files, resulting in the following error during mkdocs build or mkdocs serve:

INFO    -  Cleaning site directory 
WARNING -  Documentation file 'getting_started/brachistochrone.md' contains a link to 'getting_started/figures/TestClass.test_method_1.png' which is not found in the documentation files. 
INFO    -  Documentation built in 2.60 seconds 

Is there a proper way to have mkdocs-macros place an image file into the docs directory?
Running mkdocs build twice will work around this issue, but it seems like there should be a better way to accomplish this.

The macro:

    @env.macro
    def embed_test_plot(reference, index=1, alt_text=''):
        test_case, test_method = reference.split('.')[-2:]
        testcase_obj = get_object_from_reference('.'.join(reference.split('.')[:-1]))
        test_dir = Path(inspect.getfile(testcase_obj)).parent
        plot_file = test_dir.joinpath('_output').joinpath(f'{test_case}.{test_method}_{index}.png')

        dir_path = get_parent_dir(env)
        dest_path = dir_path.joinpath(f'figures')
        shutil.copy(plot_file, dest_path)

        return f'![{alt_text}](figures/{test_case}.{test_method}_{index}.png)'

And the get_object_from_reference function:

def get_object_from_reference(reference):
    split = reference.split('.')
    right = []
    module = None
    while split:
        try:
            module = importlib.import_module('.'.join(split))
            break
        except ModuleNotFoundError:
            right.append(split.pop())
    if module:
        for entry in reversed(right):
            module = getattr(module, entry)
    return module

When starting mkdocs serve, the following error:

mkdocs serve
mkdocs : INFO - Building documentation...
At line:1 char:1

  • mkdocs serve
  •   + CategoryInfo          : NotSpecified: (INFO    -  Building documentation... :String) [], RemoteException
      + FullyQualifiedErrorId : NativeCommandError
    
    

Traceback (most recent call last):
File "C:\Python38\Scripts\mkdocs-script.py", line 11, in
load_entry_point('mkdocs==1.1', 'console_scripts', 'mkdocs')()
File "C:\Python38\lib\site-packages\click\core.py", line 764, in call
return self.main(*args, **kwargs)
File "C:\Python38\lib\site-packages\click\core.py", line 717, in main
rv = self.invoke(ctx)
File "C:\Python38\lib\site-packages\click\core.py", line 1137, in invoke
return process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Python38\lib\site-packages\click\core.py", line 956, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Python38\lib\site-packages\click\core.py", line 555, in invoke
return callback(*args, **kwargs)
File "C:\Python38\lib\site-packages\mkdocs_main
.py", line 140, in serve_command
serve.serve(
File "C:\Python38\lib\site-packages\mkdocs\commands\serve.py", line 141, in serve
config = builder()
File "C:\Python38\lib\site-packages\mkdocs\commands\serve.py", line 122, in builder
config = load_config(
File "C:\Python38\lib\site-packages\mkdocs\config\base.py", line 197, in load_config
errors, warnings = cfg.validate()
File "C:\Python38\lib\site-packages\mkdocs\config\base.py", line 107, in validate
run_failed, run_warnings = self.validate()
File "C:\Python38\lib\site-packages\mkdocs\config\base.py", line 62, in validate
self[key] = config_option.validate(value)
File "C:\Python38\lib\site-packages\mkdocs\config\config_options.py", line 130, in validate
return self.run_validation(value)
File "C:\Python38\lib\site-packages\mkdocs\config\config_options.py", line 591, in run_validation
plgins[item] = self.load_plugin(item, cfg)
File "C:\Python38\lib\site-packages\mkdocs\config\config_options.py", line 599, in load_plugin
Plugin = self.installed_plugins[name].load()
File "C:\Python38\lib\site-packages\pkg_resources_init
.py", line 2445, in load
return self.resolve()
File "C:\Python38\lib\site-packages\pkg_resources_init
.py", line 2451, in resolve
module = import(self.module_name, fromlist=['name'], level=0)
File "C:\Python38\lib\site-packages\macros\plugin.py", line 19, in
from mkdocs.utils import string_types
ImportError: cannot import name 'string_types' from 'mkdocs.utils' (C:\Python38\lib\site-packages\mkdocs\utils__init
__.py)
mkdocs-err

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.