mistletoe icon indicating copy to clipboard operation
mistletoe copied to clipboard

Get parent token

Open vallentin opened this issue 7 years ago • 0 comments

I've implemented a custom HTMLRenderer, where I want to know if render_image is the only element on a paragraph.

Essentially be able to differentiate the output between these:

Foo ![](foobar.png) Bar

![](foobar.png)

This could be possible if token has a parent attribute.

class TestRenderer(HTMLRenderer):
    def render_image(self, token):
        has_more = len(token.parent.children) > 1
        if has_more:
            ...
        else:
            ...

Currently I have a _set_parent function, that is applied to Document in render. However it would be nice, if this was part of mistletoe and done as children are added to the token.

from mistletoe import HTMLRenderer
from mistletoe.block_token import Document

def _set_parent(parent):
    if hasattr(parent, "children"):
        for child in parent.children:
            setattr(child, "parent", parent)
            _set_parent(child)

class TestRenderer(HTMLRenderer):
    def render(self, token):
        if isinstance(token, Document):
            _set_parent(token)
        return super().render(token)

    def render_image(self, token):
        has_more = len(token.parent.children) > 1
        ...

vallentin avatar Nov 15 '18 13:11 vallentin