docs/source/dynamic.rst
Dynamic siteblocks
==================
.. _tag-dynamic:
*Dynamic* siteblocks instead of *Static* ones allows complex logic to build siteblock contents.
Siteblocks content in this case is not defined using Django Admin contrib, but generated by an ordinary Python function registered as a siteblock.
Use `register_dynamic_block()` function to register a callable that produces contents for a dynamic block.
Such a callable will get the following kwargs when called:
* `block_alias` - block alias,
* `block_context` - template context for block
Let's implement quotes siteblock similar to that from :ref:`Getting started <tag-quickstart>`, but *dynamic* this time.
1. Add `{% siteblock "my_quotes" %}` tag where you need it in templates. Here ``my_quotes`` is the alias of a block.
.. code-block:: html
{% extends "_base.html" %}
{% load siteblocks %}
{% block sidebar %}
<div class="quote">
{% siteblock "my_quotes" %}
</div>
{% endblock %}
2. Define and register a dynamic siteblock.
.. code-block:: python
# Put the following code somewhere where it'd be triggered as expected. E.g. in app view.py.
from random import choice
# Import the register function.
from siteblocks.siteblocksapp import register_dynamic_block
# The following function will be used as a block contents producer.
def get_quote(**kwargs):
quotes = [ # From Terry Pratchett's Discworld novels.
'Ripples of paradox spread out across the sea of causality.',
'Early to rise, early to bed, makes a man healthy, wealthy and dead.',
'Granny had nothing against fortune-telling provided it was done badly by people with no talent for it.',
'Take it from me, there\'s nothing more terrible than someone out to do the world a favour.',
'The duke had a mind that ticked like a clock and, like a clock, it regularly went cuckoo.',
'Most gods find it hard to walk and think at the same time.',
'They didn\'t have to be funny - they were father jokes',
'Speak softly and employ a huge man with a crowbar.',
]
return choice(quotes)
# And we register our siteblock.
register_dynamic_block('my_quotes', get_quote)