pavittarx / editorjs-html

A javascript library to parse editorjs clean data to html. It is adaptable and usable in all kind of projects.
https://runkit.com/pavittarx/editorjs-html-example
MIT License
331 stars 61 forks source link

Wrap an <img /> with <div> #6

Closed ssuvorov closed 4 years ago

ssuvorov commented 4 years ago

Allows cropping an image with CSS. e.g.

.image-wrapper {
  max-height: 400px;
  display: flex;
  overflow: hidden;

  img {
    min-width: 100%;
    height: 100%;
    align-self: center;
  }
}
pavittarx commented 4 years ago

Hey, @ssuvorov editorjs-htmlis just a parsing library. It is not meant to describe how your HTML should be. However, it can help you parse data in any way you want. But, you can render your editorjs data any way you want. For a special case like yours, you simply have to do this --

const edjsHTML = require("editorjs-html");

const parserFunctions = {
  // This will now start rendering all Image blocks in a way you want.
  image: (block) =>{
    let caption = block.data.caption ? block.data.caption : "Image";
    return `<div className="image-wrapper"><img src="${block.data.file.url}" alt="${caption}" /><div>`;
  }
}

const edjsParser = edjsHTML(parserFunctions); 

Now all the image blocks will be rendered only the way you want them to be rendered.

ssuvorov commented 4 years ago

@pavittarx Ah, okay. That works! I didn't want to parse HTML again on the client-side just to wrap an image. Thanks

ssuvorov commented 4 years ago

a minor thing: it's not a className but class. I was confused. It's an HTML, not JSX

pavittarx commented 4 years ago

@ssuvorov the new parserFunction you provide will override the one that exist by default. The default one will not be executed at all. So, nothing is parsed twice.

I used the code from the pull request you made, so that you don't have issues with it. The library doesn't check if the parsed result is valid HTML or any HTML at all. Hence, it is upto you how you would want to use it.

Interesting Fact: If you want to parse editorjs data to Markdown, you can even do so by defining your own parser functions.