XF 2.2 Adding macro content inside bb_code in Templater?


Summary: I'm wanting to inject a macro into the middle of a bb_code post and it's coming out as raw html. How do I get it to render correctly?

In a modification of post_macros:post_user_content I have some extra info that goes with the bb_code url/media blocks present in the post and I would like to display this next to each of those blocks. The extra_info contains relationships between the bbcoded form of a url and another entity I have, kind of like this:
[URL unfurl='true']https://www.whatever.com[/URL] entity 108
[MEDIA type="facebook"]https://facebook.com/stuff[/MEDIA]entity 109

I can extend Templater so that I'm calling my own function in place of {{ bb_code($post.message, 'post', $post) }}. My version is {{ render_with_buttons($extra_info, $post.message, 'post', $post)}} which calls the renderWithButtons method on my Templater extension:

    public function renderWithButtons($templater, &$escape, $extra_info, $bbCode, $context, $content, array $options = [], $type = 'html')
        $escape = false;

        foreach ($extra_info as $info) {
            $buttonBit = $this->renderMacro('my_addon_macros', 'my_addon_buttons', ['info' => $info]);
            $bbCode = str_replace($info->url_link, $info->url_link.$buttonBit, $bbCode);
        return $this->app->bbCode()->render($bbCode, $type, $context, $content, $options);

So this looks for the matching bit of bbCode and sticks the macro in after it. But the rendering is happening in the wrong place. It puts the rendered html of my macro inside the bbcode and then the bbcode turns it into raw html on the page. I understand why that happens (as that's what I've told it!) but what I can't figure out is the right order or process to follow to get the macro rendered in the right place, and the bbcode unfurled and rendered in the right place as well. THis is the closest I've got to what I want. The browser page (not the source code) ends up looking like:

[Nice box with url preview of https://www.whatever.com]
<div class='x'>
entity 108 button stuff in here

where the last lines are the contents of my_addon_buttons macro.

How do I get those lines of code from the macro to be interpreted as html by the browser rather than escaped?

I feel like maybe I'm looking in the wrong place and I ought to be trying to amend the various templates that are used to render the url/media info (e.g. _media_site_embed_facebook, bb_code_tag_url_unfurl etc) but I can't see how I can pass my $extra_info stuff through to those?


Well, I've just worked around this by changing the method above to put a placeholder bit into the bbcode which gets ignored by the bbcode rendering (because it's just text) and then changing the placeholder to the rendered macro afterwards. But I really feel I'm making it complicated and missing something obvious, so if anyone can point me in a better direction I'd appreciate it. But what I have works for now.