'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.
Solution 1:[1]
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;
}
}
Solution 2:[2]
It can be done - see https://makecode.microbit.org/. If you create a block then edit as Javascript, you can edit and (if it's valid code) then it will show the correct blocks when you switch back to the block view. The javascript is a bit odd that it's generates - so don't expect it to turn any javascript into blocks...
This isn't part of Blockly - and I'm not sure how this has been done - just that it exists - hope this helps.
Solution 3:[3]
I don't remember seeing this feature in blockly, but it is definitely possible. You will have to write custom parsers for your language code and then build the blocks accordingly.
This was somewhat explored in this answer.
Basically as and when you parse the code, you need to programatically create the blocks and attach them together to create the program in blockly.
Solution 4:[4]
we're working on a python to blocks system here https://github.com/pi-top/pi-top-blockly/ its for internal use in our education/maker site Further but the bits that might be useful are in a library here https://github.com/pi-top/pi-top-blockly/tree/main/src/utils/piBlocks it takes a python string and returns XML for blockly to use. It uses skulpt.js as a python compiler front-end and then the library goes from ast->xml
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Johnson Carneiro |
| Solution 2 | AndyS |
| Solution 3 | Nithin Kumar Biliya |
| Solution 4 | James Cat |
