mdit-py-plugins icon indicating copy to clipboard operation
mdit-py-plugins copied to clipboard

Containers with attributes.

Open jsbryaniv opened this issue 4 months ago • 0 comments

Context

I was using container_plugin, but I found it was not getting the attributes from custom containers like this

::: speaker speaker-name=Bob
Hello, how are you?
:::

When markdown-it parsed the above markdown it would correctly set the class to "speaker", but it would miss the attributes.

To fix this I made a custom plugin function that also parses the container attributes

def container_plugin_attrs(md: MarkdownIt, name: str):
    """
    Markdown-it plugin for rendering containers with attributes.
    """

    # Make render function
    def _render(self, tokens, idx, options, env):
        token = tokens[idx]
        if token.nesting == 1:
            parts = token.info.strip().split()
            for part in parts[1:]:
                if "=" in part:
                    k, v = part.split("=", 1)
                    token.attrSet(k, v)
            attrs = token.attrs or {}
            attrs_str = ' '.join(f'{k}="{v}"' for k, v in attrs.items())
            return f'<div class="{name}" {attrs_str}>\n'
        else:
            return '</div>\n'

    # Register container
    md = container_plugin(md, name, render=_render)

    # Return md for chaining
    return md

Now the output will get the correct attributes. I would like to request that something like this to be integrated as an automatic feature of the container_plugin.

Also, I realize that it is possible that this already is a core feature, and I am just doing something wrong when writing my Markdown files. In that case, please tell me if I can make a quick switch to my conventions to make it compatible.

Proposal

No response

Tasks and updates

No response

jsbryaniv avatar Aug 29 '25 19:08 jsbryaniv