GrapesJS / grapesjs

Free and Open source Web Builder Framework. Next generation tool for building templates without coding
https://grapesjs.com
BSD 3-Clause "New" or "Revised" License
22.36k stars 4.05k forks source link

[Question] Translating default component names (Body, Text, Row, etc.)? #2123

Closed lajby95 closed 5 years ago

lajby95 commented 5 years ago

I want to change the names of the default components that you can drag and drop onto the canvas, so that it shows different names in the layer manager and other places, mainly because of translation into other language. Examples: Body, Text, Row, Link, Image, etc. How would I do that? layermanager

giorgiosjames commented 5 years ago

It seems the display name for a component in the canvas and the layer manager is the block's type id, with the first letter upper-cased. From what I can tell, then only way to change this is to make a new type extending the old one, with a different id, and then deleting the old type to keep things clean. Then, all blocks utilising the old type need to be changed to the new type, and their labels changed too. Here's some example code changing some of those default component names:

editor.on('load', () => {

  const translateObject = {
    'text': 'translatedText',
    'image': 'translatedImage',
    'body':'translatedBody',
    'row':'translatedRow',
    'link':'translatedLink',
  };

  const bm = editor.BlockManager;
  const dm = editor.DomComponents;

  Object.keys(translateObject).forEach((translationKey) => {
    const translationVal = translateObject[translationKey];

    const affectedBlocks = bm.getAll().filter((b) => {
      return b.attributes.content.type === translationKey;
    });

    affectedBlocks.forEach((block) => {
      block.attributes.content.type = translationVal;
      block.set('label', translationVal);
    });

    const oldType = dm.getType(translationKey);

    dm.addType(translationVal, {
      model: oldType.model,
      view: oldType.view
    });

    dm.removeType(translationKey);

  });

});
lajby95 commented 5 years ago

Thanks. This works nicely when adding new components, but say I load a preset html+css using editor.setComponents(html) and then start editing that later. The preset's HTML tags get the various component names (Text, Box, Image etc.) assigned to them automatically by GrapesJS. How would I go about editing those default names? I can't seem to find a way.

artf commented 5 years ago

You can update their names in this way. IMPORTANT: place the code in a plugin otherwise, you risk to the see updated names only with newly added components

editor.DomComponents.addType('image', {
    model: {
        defaults: { name: 'MY IMAGE', }
    }
});