Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate blocks from code in blockly?

I have a blockly application which generates some output code. Now, is it possible to write some function which will take my output code and will put corresponding blocks on workspace. For example, on this page, https://developers.google.com/blockly/

Blocks are connected to generate javascript code, But is there any way, I will give javascript code and blocks will appear on workspace.

like image 243
Suraj Narwade Avatar asked May 24 '26 21:05

Suraj Narwade


1 Answers

You can only create javascript from blocks, not blocks from javascript. However, You can export blocks to xml, and import back the xml to blocks. So you can always save your blocks anywhere you wish in xml format, and load those from xml back to your blockly workspace.

function saveBlocks() {
    var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
    // do whatever you want to this xml
}
function loadBlock(xml) { // xml is the same block xml you stored
    if (typeof xml != "string" || xml.length < 5) {
        return false;
    }
    try {
        var dom = Blockly.Xml.textToDom(xml);
        Blockly.mainWorkspace.clear();
        Blockly.Xml.domToWorkspace(Blockly.mainWorkspace, dom);
        return true;
    } catch (e) {
        return false;
    }
}
like image 83
Johnson Carneiro Avatar answered May 26 '26 12:05

Johnson Carneiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!