Creating a FAQ Accordion
Build a nested block structure where a parent "FAQ Accordion" block renders child "FAQ Item" blocks as an Alpine.js-powered accordion.
What we are building
A main "FAQ Accordion" container block that holds multiple "FAQ Item" child blocks. Each item exposes a question (Text field) and an answer (WYSIWYG field), rendered as a collapsible accordion in the frontend.
Step 1: Create the "FAQ Item" Block
Create the individual repeatable item block first.
- Navigate to Blocks in the Admin.
- Click "New Block".
- Name:
FAQ Item - Fields:
- Add a Text field labeled
Question. - Add a WYSIWYG field labeled
Answer.
- Add a Text field labeled
- Save the block.
Step 2: Create the "FAQ Accordion" Block
Create the container block that holds the FAQ items.
- Click "New Block" again.
- Name:
FAQ Accordion. - Type: ensure it's
faq-accordion. - Save the block.
Group Capability
In Kompass, any block can act as a container if you enable the "Subgroup" logic in your code or use a Group block type. For this tutorial, we will use the built-in Group capability.
Step 3: Implement the Frontend Logic
Open your code editor and edit the two new files.
1. faq-item.blade.php
resources/views/components/blocks/faq-item.blade.php
@props(['item' => ''])
@if($item->type == 'faq-item')
<div x-data="{ open: false }" class="border-b border-gray-200 py-4">
<button @click="open = !open" class="flex justify-between items-center w-full text-left font-bold text-lg">
<span>{{ get_field('text', $item->datafield) }}</span>
<svg :class="open ? 'rotate-180' : ''" class="w-5 h-5 transition-transform" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<div x-show="open" x-collapse class="mt-2 text-gray-600">
{!! get_field('wysiwyg', $item->datafield) !!}
</div>
</div>
@endif2. faq-accordion.blade.php
resources/views/components/blocks/faq-accordion.blade.php
@props(['item' => ''])
@if($item->type == 'faq-accordion')
<div class="faq-accordion max-w-3xl mx-auto my-12">
<h2 class="text-3xl font-bold mb-8 text-center">Frequently Asked Questions</h2>
<div class="space-y-2">
@foreach ($item->children as $child)
<x-blocks.components :item="$child" />
@endforeach
</div>
</div>
@endifStep 4: Building the FAQ in the Editor
- Go to a Page and open the Block Editor.
- Add the FAQ Accordion block.
- Inside the Accordion block, click the "+" or "Add Child" button.
- Select FAQ Item.
- Fill in the question and answer. Repeat this for as many items as you need.
- Save the page.
Step 5: The Result
Navigate to your page. You now have a fully functional, interactive FAQ section where clicking a question reveals the answer with a smooth animation.
Key Takeaway
The $item->children property is the key to nesting. It allows you to loop through and render any blocks placed inside another block.