Builder plugin - preserve whitespace in <code> block


Newcomer here, so my apologies if this has been covered before. When saving a <code> block, any whitespace at the start of a line gets removed when using a textarea or markdown field as a child of a builder field.

Is there a known workaround for this issue?

Many thanks

Hey @mheys, welcome to the Kirby forum!

That seems to be a bug. I don’t know how to work around this issue, I’m afraid :thinking:

Have you tested if this also happens in a standard structure field?

Hi @texnixe!

Thanks for the reply. I’ve just tried a structure field with both textarea and markdown fields, but the problem persists too. Line breaks are respected but leading whitespaces are stripped:


Should I file this as a bug on the Kirby GitHub?

Yes please.

Oh, looks like it’s been flagged already. I’ve added a comment there, don’t want to duplicate issues.

Thanks for your help!

Thanks! I had tried to find as existing issue yesterday, but obviously looked for the wrong keywords.

Looks as if it’s not an easy thing to fix as it has been postponed to 3.4. now.

Here’s a stopgap solution for anyone who needs it. I keep any code blocks in separate fields from other content for convenience. Probably not the cleanest solution but works ok for me:

In my code field, where a space is needed I’ve put β€œ/\” like so:

.classname {
/\/\display: flex;
/\/\color: blue;

Then in my code.php snippet, I’ve replaced β€œ/\” with a space:

<?php $code = str_replace('/\\', ' ', $data->code()); ?>

<pre><?= kirbytext( $code ) ?></pre>

@mheys, many thanks for the stopgap solution. I deal with the same issue and implemented the following workaround:

In my code field, I use β€œ-” as a space, which will be replaced by four space characters. To ensure only the β€œ-” characters at the beginning of a line are replaced, I use a simple regex:

Code content in textarea:


The code.php snippet looks as follows:

<?php $codex = preg_replace('/(^-{4})/m', '                ', $data->text()) ?>
<?php $codex = preg_replace('/(^-{3})/m', '            ', $codex) ?>
<?php $codex = preg_replace('/(^-{2})/m', '        ', $codex) ?>
<?php $codex = preg_replace('/(^-)/m', '    ', $codex) ?>

This is a bit of a hack, since it only allows four intendations, but it allows to use β€œ-”, which is more comfortable :wink:

@Stefan741 Nice work! Though I’m looking forward to when this issue gets fixed and I can delete my hacky code.

Still not solved? Like to see this solved, also …