getkirby / kirby

Kirby's core application folder
https://getkirby.com
Other
1.32k stars 168 forks source link

`$blocks->excerpt()` does not seem to work #4913

Closed igregson closed 1 year ago

igregson commented 1 year ago

Description

I'm trying to get an excerpt from a layout of blocks via KQL.

From these docs, it seems I should be able to simply call $blocks->excerpt(), but this always returns an empty string.

Here's my custom fieldMethod (note the commented out code pointing out the issue, and then the code below it which is my current workaround):

/**
* @kql-allowed
*/
'createExcerptFromLayout' => function ($layoutFieldContent) {
   try {
      // From the docs this sounds like it should work but it doesn't (https://getkirby.com/docs/reference/objects/cms/blocks/excerpt).
      // $excerpt = $layoutFieldContent->toLayouts()->toBlocks()->excerpt();

      $blocks = $layoutFieldContent->toLayouts()->toBlocks();

      foreach ($blocks as $block) {
         if ($block->type() === 'textLongform') {

            $data = $block->content()->data();

            $ex = Str::excerpt($data['text'], $chars = 300);

            return $ex;
         }
      }
   } catch (\Throwable $th) {
      throw $th;
   }
},

Your setup

Kirby Version
3.8.3

distantnative commented 1 year ago

I tried to reproduce the issue, but for me it does work well both for blocks directly just from a blocks field as well as from ->toLayouts()->toBlocks().

My assumption is that it relates to your specific blocks. As Blocks::render() is based on merging Block::toHtml(), I think this is where we need to dig:

try {
    $kirby = $this->parent()->kirby();
    return (string)$kirby->snippet('blocks/' . $this->type(), $this->controller(), true);
} catch (Throwable $e) {
    if ($kirby->option('debug') === true) {
        return '<p>Block error: "' . $e->getMessage() . '" in block type: "' . $this->type() . '"</p>';
    }

    return '';
}

If the debug mode is off and there is an error with your block snippets, this would result in just empty strings. Have you tried activating the debug mode to see if you get any error messages?

afbora commented 1 year ago

I can't reproduce the issue either. createExcerptFromLayout field method works great for me as well.