Writing your own block
A SpellBlock is a class and a template. Put the class in a spellblocks.py in any installed app. It is found at startup, with no setting and no URL config. A spellblocks.py that fails to import stops startup with its error.
A worked block: steps
myapp/spellblocks.py:
from dj_spellbook import BasicSpellBlock, SpellBlockRegistry
@SpellBlockRegistry.register()
class StepsBlock(BasicSpellBlock):
name = "steps"
arguments = ("here",)
template = "myapp/steps.html"
def vet(self):
if not self.kwargs.get("here", "1").isdigit():
raise ValueError("`here` is a step number")
def get_context(self):
here = self.kwargs.get("here", "")
items = [line[2:] for line in self.content.splitlines() if line.startswith("- ")]
steps = [{"n": f"{n:02d}", "text": text, "here": here == str(n)} for n, text in enumerate(items, 1)]
return {"steps": steps}
myapp/templates/myapp/steps.html:
<ol class="steps">{% for s in steps %}<li class="step{% if s.here %} step--here{% endif %}"><span class="step-n">{{ s.n }}</span>{{ s.text }}</li>{% endfor %}</ol>
A document that uses it, and what dj-spellbook renders. The steps classes are the block's own, so the package stylesheet leaves them unstyled:
{~ steps here="3" ~}
- Tested locally
- Tested on staging
- The alpha
- Customer nodes
{~~}
- 01Tested locally
- 02Tested on staging
- 03The alpha
- 04Customer nodes
A value vet() refuses stops the document before any template runs:
{~ steps here="three" ~}
- Plan
{~~}
line 1: `steps`: `here` is a step number
What a block has to work with
nameis what the author types. Two blocks cannot share one.templateis the Django template that renders the block.argumentslists the arguments the block accepts, and it refuses any other. A block that lists none accepts anything..classand#idare always accepted.self.contentis the body exactly as written, blocks inside it unrendered, orNonefor a block that closes itself.self.kwargsholds every argument as a string: a pair under its key, a flag under its own name (opengives"open"), the classes joined by spaces underclass, and the id underid.process_content()returns the body rendered to HTML, blocks inside it included.get_context()returns what the template gets. By default that iscontent, the rendered body, plus every key ofself.kwargs.vet()refuses a bad value by raisingValueError. It runs before any template does. By default it accepts everything.
What registration refuses
@SpellBlockRegistry.register() raises Django's ImproperlyConfigured at startup when:
- the class does not extend
BasicSpellBlock; - it is missing a
nameor atemplate; - its
nameis already taken by another block.
A block with no body
A block written in its self-closing form gets None for self.content, and process_content() returns an empty string. Self-closing blocks are the only kind that may sit inside another block's body:
{~ cards ~}
{~ tile name="Admin" /~}
{~ tile name="Read-Only" /~}
{~~}