-
Notifications
You must be signed in to change notification settings - Fork 554
/
HasBlocks.php
44 lines (33 loc) · 1.51 KB
/
HasBlocks.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
namespace A17\Twill\Models\Behaviors;
use A17\Twill\Models\Block;
trait HasBlocks
{
public function blocks()
{
return $this->morphMany(Block::class, 'blockable')->orderBy(config('twill.blocks_table', 'twill_blocks') . '.position', 'asc');
}
public function renderBlocks($renderChilds = true, $blockViewMappings = [], $data = [])
{
return $this->blocks->where('parent_id', null)->map(function ($block) use ($blockViewMappings, $renderChilds, $data) {
if ($renderChilds) {
$childBlocks = $this->blocks->where('parent_id', $block->id);
$renderedChildViews = $childBlocks->map(function ($childBlock) use ($blockViewMappings, $data) {
$view = $this->getBlockView($childBlock->type, $blockViewMappings);
return view($view, $data)->with('block', $childBlock)->render();
})->implode('');
}
$block->childs = $this->blocks->where('parent_id', $block->id);
$view = $this->getBlockView($block->type, $blockViewMappings);
return view($view, $data)->with('block', $block)->render() . ($renderedChildViews ?? '');
})->implode('');
}
private function getBlockView($blockType, $blockViewMappings = [])
{
$view = config('twill.block_editor.block_views_path') . '.' . $blockType;
if (array_key_exists($blockType, $blockViewMappings)) {
$view = $blockViewMappings[$blockType];
}
return $view;
}
}