The default messages in Blockly (such as the text in the context menu) have been
translated to many different languages. The en
locale is loaded by default,
but the other available locales can be included as well.
Configuring locale with npm
When you import Blockly with import * as Blockly from 'blockly';
you'll get
the default modules: Blockly core, Blockly built-in blocks, the JavaScript
generator and the English lang files.
To use other locales, you'll want to define your imports more carefully:
Import Blockly default modules
import * as Blockly from 'blockly/core';
import 'blockly/blocks';
import 'blockly/javascript'; // Or the generator of your choice
Import Blockly languages
For example, to import the French message set:
import * as Fr from 'blockly/msg/fr';
For a full list of supported Blockly locales, see: https://github.com/google/blockly/tree/master/msg/js
Configure locale
After importing the desired message set, you'll want to set the locale in Blockly. This function is currently only included in the npm release of Blockly.
Blockly.setLocale(Fr);
This needs to be called before the workspace is loaded.
Configuring locale without npm
Include the appropriate script src from the Blockly msg directory, and the translations will be automatically included.
<script src="../../blockly_compressed.js"></script>
<script src="../../blocks_compressed.js"></script>
<script src="../../msg/js/ar.js"></script>
Custom translations
Blockly includes translations for all of its default strings, but if you have
custom blocks with text, you may wish to include your own translations for those
strings. For example, the structure of blockly/msg/es
is similar to the
following:
Blockly.Msg["COLOUR_RGB_RED"] = "rojo";
You can add additional custom messages as new properties on the Blockly.Msg
object by calling setLocale
with an object with your custom translations. You
may wish to prefix your translations with a custom prefix so that you avoid
collisions with any default translations that may be added in the future.
// In custom_es.js
export const CustomEs = {
HELLO: "Hola",
}
// In your setup code
import * as Es from blockly/msg/Es;
import { CustomEs } from ../custom_es;
Blockly.setLocale(Es);
Blockly.setLocale(CustomEs);
setLocale
puts each key from the input object into Blockly.Msg
. You can call
it multiple times with distinct keys, but calling it a second time with a
duplicate key will overwrite the first.
To reference the translated string in your block, use Blockly.Msg['HELLO']
which should contain the string for the locale you've configured.
Related topics
- Right-to-left languages: See the RTL demo
- Localizing blocks