PHP template for blocks

Based on the guides I have created a news section in my project with a blueprint, this is the important fragment:

columns:
  main:
    width: 2/3
    fields:
      content:
        label: Contenido
        type: blocks
        fieldsets: 
          - text
          - heading
          - image
          - gallery
          - video
          - markdown
        size: large

But the correspondent part of the template not works:

  <div class="article-content">
      <h1><?= $page->title() ?></h1>
      <?php if ($page->content()->isNotEmpty()): ?>
          <?php foreach ($page->content()->toBlocks() as $block): ?>
              <div class="block block-type-<?= $block->type() ?>">
                  <?= $block ?>
              </div>
          <?php endforeach ?>
      <?php endif ?>
  </div>

Why? Thanks…

content is a reserved name. So $page->content() doesn’t return your blocks Field, but rather a Content object. You can either rename the field, or access its content (ironically) via the Content object:

<?php

$myField = $page->content()->get('content');
$blocks = $myField->toBlocks();

PS: This is unrelated, but I’m not sure if isNotEmpty() correctly works with blocks fields. isNotEmpty() is (making up names here) “field type agnostic”: it simply checks whether the underlying data of a field is not an “empty string or whitespace”.
Blocks, however, are stored as JSON array in the content file, therefore, even if there are no blocks it could be serialized as an empty array ([]), that empy array however wouldn’t qualify as “empty field”.

I think that was the case in earlier versions, but was fixed at some point, so that now an empty string is stored, and isEmpty()/isNotEmpty() work as expected.

1 Like

Thanks, I think that I will make all Kirby’s newbie mistakes until the project launch but with the community’s help, I’ll finish it.