fralau / mkdocs-macros-plugin

Create richer and more beautiful pages in MkDocs, by using variables and calls to macros in the markdown code.
https://mkdocs-macros-plugin.readthedocs.io
Other
318 stars 50 forks source link

Plugin incorrectly demands existence of `define_env()` in module #191

Closed fralau closed 6 months ago

fralau commented 8 months ago

There is a requirement in the plugin.py file that the define_env() function should be present in the module file (main.py).

This was correct in the past, but nowadays it could also be on _pre_page_macros and others.

Workaround

Just add this function to the module file:

def define_env(env):
   pass
fralau commented 8 months ago

Any standard function is now accepted and the error is now explicit in case none is found:

NameError: None of the standard functions was found in module 'main':
['define_env', 'on_pre_page_macros', 'on_post_page_macros', 'on_post_build']

For good measure, the plugin also traces now the case when no module is found (it's not an error, just in case someone gave a wrong name to the module, or put it in the wrong place).

fralau commented 8 months ago

This was detected in question #190.

fralau commented 8 months ago

@Andre601 Could you please check that it works for you now?

Andre601 commented 8 months ago

Can confirm that adding the def define_env(env): line with the pass key makes it work.

Andre601 commented 8 months ago

Tho, I have to add that in my case, the on_pre_page_macros call doesn't work right? Or at least not how I want it to?

I want it to add {% import 'game.md' as game %} to the markdown itself, so that I can them use macros without having to import them first, but either the markdown isn't modified, or the import statement isn't seen as such...

The full code I use, which is basically a copy of the docs:

def on_pre_page_macros(env):
    footer = "{% import 'game.md' as game %}"
    env.markdown += footer

I also tried putting it in front of the env.markdown (At the top) in hopes that it may be an issue with order, but no luck there.

It simply gives a "game is undefined" error...

fralau commented 8 months ago

It depends on what your expectancy is of "to work".

It is a jinja2 statement, which will be executed immediately after. Indeed, it is executed (at least your error seems to be a jinja2 error). Your import statement seems incorrected formulated (see examples):

Shouldn't it be something like the following?

{% from 'game.md' import game %}
Andre601 commented 8 months ago

I've used jinja2 more than enough to know that {% import ... as ... %} works here.

Also, my fault for not mentioning that it does work, but I had to add it at the top of the page due to how jinja2 parses things.