HTMLSerializer - Grouped images

I've put this down as React butIi guess this could be for any technology.

I have a rich text field where I add text and multiple images.

If I have 2 or more images next to each other, I want to lay them out in a grid. In order to do this its ideal that they share a parent, i.e...

I've been looking at doing this in my own HTMLSerializer, but have hit a few walls. I wondered if anyone else has achieved a similar result?

Hey @thejuniperstudio,

This is a really interesting question! We had a conversation about it internally to discuss the best way to do it. The solution we came up with is a bit complex. Basically, when you render a rich text field, you pass a function invocation that accepts your Rich Text array as an argument and returns your HTML Serializer. :point_left: Let's call this the "intermediary" function. In a plain JavaScript implementation, that would look like this:


As a result, the intermediary will have inside it the rich text field that you are processing and also your HTML Serializer function (which is meant to process each element of the rich text array, one at a time). So, the intermediary will allow the HTML Serializer to compare the current element in the Rich Text array against the rest of the array and customize the output conditionally, like this:

const htmlSerializerIntermediary = (richText) => {
  const htmlSerializer = (type, element, content, children) => {
  const index = richText.findIndex((el) => JSON.stringify(el) === JSON.stringify(element))
    if (richText[index - 1]?.type === type) {
      return `<p class="sibling">${element.text}</p>`
    switch (type) {
      case Elements.paragraph:
        return `<p>${element.text}</p>`
        return `<span>${element.text}</span>`
  return htmlSerializer

Sorry, I probably didn't explain that very well! I'm still wrapping my head around it :laughing:

I've attached a file that brings it all together. (Again, this is with our basic JavaScript packages — you will need to tweak it for React.) Please take a look and let me know if it makes any sense:

complex-serializer.js (1.0 KB)


Thanks @samlittlefair
Looks like an interesting solution, which might just work! I'll have a play with it and feedback any results/changes.

1 Like

Awesome! I'll leave this thread open for a little while, in case you have any thoughts. I'll close it in a week or so, but you can always flag it to reopen and keep the discussion going :slight_smile:

This issue has been closed as it has been fixed, Flag if it is not the case for you to reopen.