Creating Custom SpellBlocks
Let's create a custom SpellBlock that makes a collapsible section - perfect for FAQs or long documentation. We'll go through the whole process:
- First, create your SpellBlock class:
from django_spellbook.blocks import BasicSpellBlock
from django_spellbook.registry import SpellBlockRegistry
@SpellBlockRegistry.register()
class CollapsibleBlock(BasicSpellBlock):
name = 'collapsible'
template = 'my_app/blocks/collapsible.html'
def get_context(self):
context = super().get_context()
context['summary'] = self.kwargs.get('summary', 'Click to expand')
context['open'] = self.kwargs.get('open', False)
return context
- Create the template at
my_app/templates/my_app/blocks/collapsible.html
:
<details class="spellbook-collapsible spellbook-border spellbook-border-radius-lg spellbook-p-3 spellbook-mb-3 spellbook-bg-light "
>
<summary class="spellbook-cursor-pointer spellbook-font-bold">
</summary>
<div class="spellbook-mt-3">
</div>
</details>
- Now you can use it in your markdown:
{~ collapsible summary="Why use SpellBlocks?" open="true" ~}
SpellBlocks make your markdown more powerful by adding:
- Custom components
- Consistent styling
- Reusable patterns
{~~}
How It Works
- The
@SpellBlockRegistry.register()
decorator adds your block to the available blocks - The
name
property sets what you'll type in markdown get_context()
processes any parameters you want to pass to your template- Your template uses Spellbook's built-in classes for consistent styling
Best Practices
- Include the
% spellbook_styles %
tag in your base template to use the built-in styles -
Use the built-in utility classes:
-spellbook-border
-spellbook-border-radius-lg
-spellbook-p-3
(padding)
-spellbook-mb-3
(margin-bottom)
-spellbook-bg-light
-spellbook-shadow-sm
-spellbook-collapsible
is also included, just so this documentation can go smoothly, but feel free to make your own. -
Allow for custom classes:
{% if kwargs.class %}{{ kwargs.class }}{% endif %}
- Use
|safe
filter for markdown content:
{{ content|safe }}
The content
variable is already processed as markdown when it reaches your template!
Want to see more examples? Check out the built-in blocks source code for inspiration!