Blockly 的大多数应用都要求将用户程序翻译为编程语言。此操作由 Blockly 在客户端执行。
生成代码
第一步是添加相关语言的生成器。Blockly 包含以下生成器:
- JavaScript
- Python
- PHP
- Lua
- Dart
您可以通过以下方法之一导入和使用生成器。
模块
import {javascriptGenerator} from 'blockly/javascript';
import {pythonGenerator} from 'blockly/python';
import {phpGenerator} from 'blockly/php';
import {luaGenerator} from 'blockly/lua';
import {dartGenerator} from 'blockly/dart';
const jsCode = javascriptGenerator.workspaceToCode(workspace);
const pythonCode = pythonGenerator.workspaceToCode(workspace);
const phpCode = phpGenerator.workspaceToCode(workspace);
const luaCode = luaGenerator.workspaceToCode(workspace);
const dartCode = dartGenerator.workspaceToCode(workspace);
卸载
您必须先添加 Blockly,然后才能添加生成器。
<script src="https://unpkg.com/blockly"></script>
<script src="https://unpkg.com/blockly/javascript_compressed"></script>
<script src="https://unpkg.com/blockly/python_compressed"></script>
<script src="https://unpkg.com/blockly/php_compressed"></script>
<script src="https://unpkg.com/blockly/lua_compressed"></script>
<script src="https://unpkg.com/blockly/dart_compressed"></script>
const jsCode = javascript.workspaceToCode(workspace);
const pythonCode = python.workspaceToCode(workspace);
const phpCode = php.workspaceToCode(workspace);
const luaCode = luna.workspaceToCode(workspace);
const dartCode = dart.workspaceToCode(workspace);
本地脚本
您必须先添加 Blockly,然后才能添加生成器。
<script src="blockly_compressed.js"></script>
<script src="javascript_compressed.js"></script>
<script src="python_compressed.js"></script>
<script src="php_compressed.js"></script>
<script src="lua_compressed.js"></script>
<script src="dart_compressed.js"></script>
const jsCode = javascript.workspaceToCode(workspace);
const pythonCode = python.workspaceToCode(workspace);
const phpCode = php.workspaceToCode(workspace);
const luaCode = lua.workspaceToCode(workspace);
const dartCode = dart.workspaceToCode(workspace);
实时生成
生成代码是一项非常快的操作,因此频繁调用此函数没有坏处。一种常见的策略是通过向 Blockly 的更改事件添加监听器来实时生成并显示代码:
import {javascriptGenerator} from 'blockly/javascript';
function updateCode(event) {
const code = javascriptGenerator.workspaceToCode(workspace);
document.getElementById('textarea').value = code;
}
workspace.addChangeListener(updateCode);
如需了解详情,请参阅事件。