Insert one grasshopper definition into the canvas of an active file

I’m trying to make a template node that, when activated, can place an existing definition on the canvas. This is like the template components provided by both Eddy3D and climate studio. I’ve had limited luck with “GrasshopperDocument.AddObject” for placing individual nodes but I get the feeling that doing this for dozens of individual components would be a mistake. Thanks in advance for any help.[Eddy Templates] for reference (https://www.eddy3d.com/support/documentation/)

Hi @jeffrey.moser ,
You could create a template file with the node, and then merge your template document to the current document using GH_Document.Merge()

            string templatePath = ""; //path of template file
            GH_Archive gH_Archive = new GH_Archive();
            gH_Archive.ReadFromFile(templatePath);
            using (GH_Document templateDocument = new GH_Document())
            {
                gH_Archive.ExtractObject(templateDocument, "Definition");
                Instances.ActiveCanvas.Document.MergeDocument(templateDocument);
            }

Hey @Darryl_Menezes, this is great! thankyou. One thing is that .ExtractObject doesn’t seem to grab the connectivity graph of the gh definition so the nodes come in without wires.

Hi @jeffrey.moser ,

Perhaps it was the “using” statement. Try this:

            GH_Archive gH_Archive = new GH_Archive();
            gH_Archive.ReadFromFile(templatePath);
            GH_Document templateDocument = new GH_Document();

            gH_Archive.ExtractObject(templateDocument, "Definition");
            
            foreach(var obj in templateDocument.Objects)
            {
                if(obj is GH_ActiveObject activeObject)
                {
                    activeObject.CollectData();
                    activeObject.ComputeData();
                }
            }

            Instances.ActiveCanvas.Document.MergeDocument(templateDocument, true, true);
            Instances.ActiveCanvas.Document.ExpirePreview(true);
1 Like

Hi @Darryl_Menezes thanks for you answer!

It works great, but I can only import the template once otherwise it raises an exception saying “An entry with the same key already exists.”

Do you know how could I import these objects multiple times? I imagine that I’d have to read from the template and create new component instances one by one?

EDITED ----
Was able to solve it using templateDocument.MutateAllIds() before merging the documents