Using custom JavaScript Generators

Generators convert blocks into a text string, usually a traditional programming language. Blockly for Android uses the same JavaScript generator framework as the original web Blockly, and by default generates JavaScript.

Loading generator functions

For activities that extend AbstractBlocklyActivity, the generator files are provided by overriding AbstractBlocklyActivity.getGeneratorsJsPaths(). The activity must implement this method, returning a list of application asset paths pointing to the desired generators. These are loaded in addition to the JavaScript language core generator files for Blockly's standard blocks. This method is called every time code generation is triggered, so the list can be dynamic or contextual.

Just like block definition files, multiple .js files can be loaded. The files are loaded in order, so duplicate ids (referring to the block definitions) will result in replacing prior generator definitions.

Example JavaScript block implementation

The following is an example of a generator used in the Turtle demo.

Blockly.JavaScript['turtle_width'] = function(block) {
  // Generate JavaScript for setting the width.
  var width = Blockly.JavaScript.valueToCode(block, 'WIDTH',
      Blockly.JavaScript.ORDER_NONE) || '1';
  return 'Turtle.penWidth(' + width + ');\n';

This code is found in blocklydemo/assets/turtle/generators.js, beside the matching block definitions in blocklydemo/assets/turtle/turtle_blocks.js. TurtleActivity.getGeneratorsJsPaths returns this path, via the constant TURTLE_BLOCK_GENERATORS.

The function genetates the code for turtle_width blocks, taking in the code string generated for its WIDTH input (or '1', if unset), and wrapping in a Turtle.penWidth(..) function call. The results might look like any of these:

Turtle.penWidth(x / 2);

For more details on writing generators, see Generating Code.

Using other languages

Blockly for Android assumes the target language is JavaScript by default. If you want to use another language, override AbstractBlocklyActivity.getBlockGeneratorLanguage and return a language definition with the path to the core language file and the object which defines the generator functions.

protected LanguageDefinition getBlockGeneratorLanguage() {
    return new LanguageDefinition("lua/lua_compressed.js", "Blockly.Lua");

The main Blockly repository has generators for several popular languages.

How the generators are run

Blockly for Android maintains a WebView in a background service to run the generators written in JavaScript. The code is in the CodeGeneratorService class. Most app developers should only need the higher level APIs provided by extending AbstractBlocklyActivity, and can ignore this detail.