Grapesjs: [Question] Custom request on "src" attributes

Created on 14 Nov 2018  路  3Comments  路  Source: artf/grapesjs

I implemented a small GrapesJS editor that allows to edit Django/Jinja2 templates. GrapesJS by default is trying to GET the image preview of my element:

<a href="{{product_url}}" target="_blank"><img src="{{image_url}}" width="130"/></a>

The request happens everytime I load the template into the GrapesJS editor:
http://localhost:8000/%7B%7Bimage_url%7D%7D 404 (Not Found)

GrapesJS editor though works fine even with this 404 call. But I would like to do handle the request to the image. So instead of GrapesJS making a default call to http://localhost:8000/%7B%7Bimage_url%7D%7D I would like to render a placeholder image let's say: https://placekitten.com/200/300

My current configuration:

editor = grapesjs.init({
      container: '#gjs',
      assetManager: {},
});

editor.setComponents('<a href="{{product_url}}" target="_blank"><img src="{{image_url}}" width="130"/></a>');

// querySelector is returning an empty Array of Nodes
editor.on('load', () => {
      const body = editor.Canvas.getBody().ownerDocument;
      body.querySelectorAll('a').forEach(function(el) {
          let link = el;
          link.setAttribute('src', "http://via.placeholder.com/350x150");
      });
      editor.store();
});

How can this be achieved with Grapes ?

enhancement outdated

Most helpful comment

Hi @mathiasbc by using the latest https://github.com/artf/grapesjs/releases/tag/v0.14.43
It should work with something like this

editor.on('component:mount', model => {
  if (model.is('image')) {
      if (model.get('src') == '{{image_url}}') {
        model.getEl().src = "http://via.placeholder.com/350x150";
      }
  }
});

All 3 comments

Hi Mathias, currently the only possibility I see now is to extend the image component and its render() method. Probably I'll add some new component event to make such a case easier to manage

Hi @mathiasbc by using the latest https://github.com/artf/grapesjs/releases/tag/v0.14.43
It should work with something like this

editor.on('component:mount', model => {
  if (model.is('image')) {
      if (model.get('src') == '{{image_url}}') {
        model.getEl().src = "http://via.placeholder.com/350x150";
      }
  }
});

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

YashPrince picture YashPrince  路  3Comments

tribulant picture tribulant  路  3Comments

kickbk picture kickbk  路  3Comments

Geczy picture Geczy  路  3Comments

desilvaNSP picture desilvaNSP  路  3Comments