Skip to content

Containers with attributes. #129

Description

@jsbryaniv

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions