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

Is it possible to use Metadata in module? #223

Closed steele-ntwrk closed 4 months ago

steele-ntwrk commented 4 months ago

Hi All,

I am trying to use the page metadata to pass in a variable to a macro's module I have written. I have provided the module and the page data below.

In short the metadata renders using simple Jinja, the module works if I pass in the site name as the variable i.e "TEST" however the module doesnt work if I use

{% for vlan in get_vlans_for_site('site_name') %}

or

{% for vlan in get_vlans_for_site('{{site_name}}') %}

Module


def define_env(env):

    # Define global variables
    env.variables['netbox_url'] = 'https://192.168.40.163'
    env.variables['netbox_api_token'] = 'd9ad849f860d24b653c6a2072fff1afb3d8cf49f'

    # Define a macro to get VLANs for a given site
    @env.macro
    def get_vlans_for_site(site_name):
        headers = {
            'Authorization': f'Token {env.variables["netbox_api_token"]}',
            'Accept': 'application/json',
        }
        sites_response = requests.get(f"{env.variables['netbox_url']}/api/dcim/sites/?name={site_name}", headers=headers, verify=False)
        site_id = sites_response.json()['results'][0]['id']

        vlans_response = requests.get(f"{env.variables['netbox_url']}/api/ipam/vlans/?site_id={site_id}", headers=headers, verify=False)
        return vlans_response.json()['results']

Page

---
Version: 1.0
Author: Steele Network
Classification: Unclassified
site_name: TEST
---

### Functional Specifications
{{site_name}} # This renders

{% for vlan in get_vlans_for_site('site_name') %} # This does not render and presents a error, I put in the site name "TEST" in their it renders correctly. 
- VLAN ID: {{ vlan.vid }}, Name: {{ vlan.name }}, Description: {{ vlan.description | default('No description', true) }}
{% endfor %}
github-actions[bot] commented 4 months ago

Welcome to this project and thank you!' first issue

steele-ntwrk commented 4 months ago

I fixed it myself by remove the quotations around site_name

{% for vlan in get_vlans_for_site(site_name) %}

fralau commented 4 months ago

That's good. Indeed, the syntax is very much like Python (site_name is a variable).

If I were you, I would not publish api tokens on github?

I convert this issue into a discussion.