Custom Gutenberg Block: How to return plain HTML with save(), without escaping?

I'm writing a custom Gutenberg editor block.

When saving the block I can save simple HTML elements, like in the documentation:

return wp.element.createElement('div', blockProps, 'Your block.');

However, I need to return some huge and complicated HTML that I cannot produce in that way. To give you an impression:

div class=wrappersvg class=some-svg-image version=1.1 xmlns=http://www.w3.org/2000/svg xmlns:xlink=http://www.w3.org/1999/xlink x=0px y=0px viewBox=0 0 600 600 xml:space=preserve aria-labelledby=catTitle catDesc role=img...g...path.../svg/div

When I return this as a string, it will be escaped.

How can I prevent escaping for the HTML that I return with the save() method?

Topic block-editor Wordpress

Category Web


From the docs:

While it is possible to return a string value from save, it will be escaped. If the string includes HTML markup, the markup will be shown on the front of the site verbatim, not as the equivalent HTML node content. If you must return raw HTML from save, use wp.element.RawHTML. As the name implies, this is prone to cross-site scripting and therefore is discouraged in favor of a WordPress Element hierarchy whenever possible.

In addition, you can also import the SVG as a component and use it as you would use any other JSX / React, e.g. via svgr.

return (
    <div className="wrapper">
        <svg className=".."..>
        ...
        </svg>
    </div>
);

would become

import MyIcon from '../../assets/myicon.svg';

...

return (
    <div className="wrapper">
        <MyIcon />
    </div>
)

(Here I'm using JSX <div> instead of ...createElement('div', ..) which is basically the same but imo a more readable syntax.)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.