Fields are an important part of code generation, because they define user-editable values like strings, numbers, and colours (among others).
Including field values in generated code involves getting the field's value, transforming it into a usable string, and then concatenating the string with the rest of the code.
import {javascriptGenerator} from 'blockly/javascript';
javascriptGenerator.forBlock['my_custom_block'] = function(block, generator) {
// Get the field value.
const fieldValue = block.getFieldValue('MY_FIELD');
// Concatenate the code.
const code = `some code ${fieldValue} some more code`;
// Return the code.
return code;
}
Get values
Field values can be accessed using getFieldValue
. What gets
returned is different from field to field, so you should check the built-in
field documentation for info about your specific field. For
example, text input fields return the exact text the user entered, but dropdown
fields return a language-neutral string associated with the item the user
selected.
Transform values
Most field values are ready to be concatenated to your code string immediately. However, some field values require extra work before they are usable.
Strings
Strings need to be quoted by the code generator before they can be concatenated.
// For a single line text field.
const str = generator.quote_(block.getFieldValue('STR'));
// For a multiline text field.
const str = generator.multiline_quote_(block.getFieldValue('STR'));
Variables
Variable names need to be scrubbed by the code generator before they can be concatenated. This is necessary for two reasons:
- Variables are entered by the user in their language of choice. This means they
may need to be converted to ASCII characters. For example, "
متغير
" would get converted to "_D9_85_D8_AA_D8_BA_D9_8A_D8_B1
". - Variables may conflict with reserved words. This means they may need to be
modified so they don't conflict. For example, "
for
" would get converted to "for2
".
const identifier = generator.getVariableName(block.getFieldValue('VAR'));
Concatenate code
Once you've gotten your field's value and converted it to a string, you can concatenate it in the correct place with your code string.
const code = `some code ${value} some more code`;
Return code
Different types of blocks require the code string to be returned in different ways, so check out their individual pages for more information: