Skip to content

Commit 3689d26

Browse files
committed
feat: add getUsedBlockTypesFromLayouts()
1 parent d7c5b7c commit 3689d26

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

src/misc.php

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -371,7 +371,7 @@ function buildMailtoLink(string $email, string|null $subject = null, string|null
371371
* Useful for conditional CSS loading based on which blocks are used on a page.
372372
*
373373
* @param \Kirby\Cms\Blocks|array $blocks The blocks to analyze.
374-
* @return array An array of unique block type strings.
374+
* @return array An array of block type strings.
375375
*
376376
* @example
377377
* $blockTypes = getUsedBlockTypes($page->text()->toBlocks());
@@ -390,7 +390,39 @@ function getUsedBlockTypes(\Kirby\Cms\Blocks|array $blocks): array
390390
$types[] = $block->type();
391391
}
392392

393-
return array_unique($types);
393+
return $types;
394+
}
395+
}
396+
397+
/**
398+
* Extract all used block types from a Layouts object or array of layouts.
399+
* Iterates through all layouts, their columns, and blocks to find all used block types.
400+
*
401+
* @param \Kirby\Cms\Layouts|array $layouts The layouts to analyze.
402+
* @return array An array of block type strings.
403+
*
404+
* @example
405+
* $blockTypes = getUsedBlockTypesFromLayouts($page->sections()->toLayouts());
406+
* // returns ['heading', 'text', 'image', 'gallery']
407+
*
408+
* @example with cssIfBlock
409+
* $pageBlocks = getUsedBlockTypesFromLayouts($page->sections()->toLayouts());
410+
* cssIfBlock('assets/css/gallery.css', 'gallery', $pageBlocks);
411+
*/
412+
if (!function_exists('getUsedBlockTypesFromLayouts')) {
413+
function getUsedBlockTypesFromLayouts(\Kirby\Cms\Layouts|array $layouts): array
414+
{
415+
$types = [];
416+
417+
foreach ($layouts as $layout) {
418+
foreach ($layout->columns() as $column) {
419+
foreach ($column->blocks() as $block) {
420+
$types[] = $block->type();
421+
}
422+
}
423+
}
424+
425+
return $types;
394426
}
395427
}
396428

0 commit comments

Comments
 (0)