1

I want to add a custom data attribute to an image tag (say, data-filename="abc.jpeg"), that can store certain meta-data in Quill editor. I tried attributors in Quill, but couldn't succeed in getting the job done.

Could anyone help please.

Aswin Rajeev
  • 97
  • 1
  • 10

2 Answers2

3

Solved the issue. I created a new blot by extending the Quill image format.

const ImageBlot = Quill.import('formats/image');
export class CustomImageBlot extends ImageBlot {

  static blotName = 'customImage';
  static tagName = 'img';

  /**
   * Converts the HTML tag to image blot
   * @param value 
   */
  static create(value) {

    let node = super.create();

    node.setAttribute('src', value.url);
    node.setAttribute('data-attr', value.data);

    return node;
  }

  /**
   * Converts the image blot to HTML tag
   * @param node 
   */
  static value(node) {

    var blot = {};

    blot.url = node.getAttribute('url');
    blot.data_attr = node.getAttribute('data-attr');

    return blot;
  }
}

Thanks a lot Loa for the suggestion for edit. I was able to solve a few of the issues with default support of the image format.

Aswin Rajeev
  • 97
  • 1
  • 10
  • Hi. I was going to answer your question today. Glad you were able to solve your problem. I just want to make an addition: In your particular case, you do not need to create an image blot from scratch, as you can take advantage of all the features already implemented in the image blot itself. For example, take a look at this [code](https://github.com/loagit/Quill-Examples-and-FAQ/blob/master/Quill%20Project%20002%20-%20Centralized%20Video/app.js#L91). This can save you work. In the example shown, the video input tooltip is reused without the need to write a new one. – Loa Dec 28 '19 at 13:42
  • Thanks a lot Loa. That indeed solved a lot of issues. :) – Aswin Rajeev Dec 29 '19 at 12:37
0

I extended your answer to accept all attributes originally passed to the img element. I do not understand why quill removes it.

    // Allow img to have all attributes passed originally
    const ImageBlot = Quill.import("formats/image");
    export class CustomImageBlot extends ImageBlot {
      static blotName = "customImage";
      static tagName = "img";
    
      /**
       * Converts the HTML tag to image blot
       * @param value
       */
      static create(value) {
        let node = super.create();
        Object.getOwnPropertyNames(value).forEach((attribute_name) => {
          node.setAttribute(attribute_name, value[attribute_name]);
        });
    
        return node;
      }
    
      /**
       * Converts the image blot to HTML tag
       * @param node
       */
      static value(node) {
        var blot = {};
        node.getAttributeNames().forEach((attribute_name) => {
          blot[attribute_name] = node.getAttribute(attribute_name);
        });
    
        return blot;
      }
    }
    
    Quill.register(CustomImageBlot);
Aswin Rajeev
  • 97
  • 1
  • 10
Daedra22
  • 16
  • 3