flanger.dev

How to Import HTML Text as Structured Data to Bard

If you want to migrate from another CMS to Statamic you might wonder how you can import HTML text to the Statamic Bard field type as structured data.

Image of the code required to migrate html text to bard data structure

Why do you want to do this?

You may ask why would you even want to import your HTML text back to structured data, when the Bard field type also allows you to save everything as HTML? Well, I'm glad you ask, because there is one significant downside to that. You cannot use the great feature of Bard that allows you to add "sets" to your field, if you activate save_html in the field options.

The documentation for the save_html option says:

Only works while no sets are defined. Default: false.

Advantages of Sets

Why are Bard sets so great? Because you can add and position content elements like images, code blocks or any other elements directly into your text! You can read all the features in the documentation.

How you can migrate your HTML Text

To migrate your HTML text you need to create a new instance of HtmlToProseMirror\Renderer and call the render method and then access the 'content' array key as shown in the example:

1$entry = Entry::make()->collection('pages')->data(
2 [
3 'text' => (new \HtmlToProseMirror\Renderer)->render('your HTML Text')['content'],
4 ]);
5 
6$entry->save();

Doing so provides the bard field the structured data it expects, and you can enjoy having migrated all your content with the ability of using sets in your bard fields!