Add entries to the gallery node

    Should happen when all the doctrees have been read
    and the gallery entries have been collected. i.e at
    doctree-resolved time.

def add_entries_to_gallery(app, doctree, docname):
    """
    Add entries to the gallery node

    Should happen when all the doctrees have been read
    and the gallery entries have been collected. i.e at
    doctree-resolved time.
    """
    if docname != 'gallery':
        return

    if not has_gallery(app.builder.name):
        return

    # Find gallery node
    try:
        node = doctree.traverse(gallery)[0]
    except TypeError:
        return

    content = []
    for entry in app.env.gallery_entries:
        raw_html_node = nodes.raw('', text=entry.html, format='html')
        content.append(raw_html_node)

    # Even when content is empty, we want the gallery node replaced
    node.replace_self(content)