Most applications of Blockly require the user's program to be translated into JavaScript, Python, PHP, Lua, Dart, or some other language. This action is performed on the client side by Blockly.
Generating Code
The first step is to include the generator for the language in question. Blockly includes the following generators:
-
javascript_compressed.js
-
python_compressed.js
-
php_compressed.js
-
lua_compressed.js
-
dart_compressed.js
The generator class should be included right after blockly_compressed.js
.
For example, here is the JavaScript generator included:
<script src="blockly_compressed.js"></script>
<script src="javascript_compressed.js"></script>
The user's blocks may be exported to code at any time from your application with this call:
var code = Blockly.JavaScript.workspaceToCode(workspace);
Replace JavaScript
with Python
, PHP
, Lua
, or Dart
in both preceding lines to
switch the language generated.
Realtime Generation
Generating code is an extremely fast operation, so there's no harm in calling this function frequently. A common strategy is to generate and display code in realtime by adding a listener to Blockly's change event:
function myUpdateFunction(event) {
var code = Blockly.JavaScript.workspaceToCode(workspace);
document.getElementById('textarea').value = code;
}
workspace.addChangeListener(myUpdateFunction);
See Events for more information.