Dynamic trees allow you to compose and register sitetrees at runtime (e.g., in config.ready() or urls.py) rather than relying solely on database-stored trees. This is useful for structuring app-defined trees into existing hierarchies dynamically.
To use dynamic trees, you must:
- Use
compose_dynamic_tree() to create a tree structure or gather trees from an app. - Register them using
register_dynamic_trees(). - (Optional) Set
SITETREE_DYNAMIC_ONLY = True in your settings to prevent the application from querying the database for trees/items, which is efficient if you only use dynamic trees.
When calling register_dynamic_trees(), you can use the reset_cache=True argument to ensure newly registered trees are rendered immediately by dropping and recreating the cache.
from sitetree.toolbox import tree, item, register_dynamic_trees, compose_dynamic_tree
register_dynamic_trees(
# Gather all trees from the 'books' app
compose_dynamic_tree('books'),
# Gather trees from 'books' and attach them to the 'main' tree root
compose_dynamic_tree('books', target_tree_alias='main'),
# Gather trees from 'books' and attach them to a specific item in 'main' tree
compose_dynamic_tree('books', target_tree_alias='main', parent_tree_item_alias='for_books'),
# Define a tree structure directly during registration
compose_dynamic_tree((
tree('dynamic', items=(
item('dynamic_1', 'dynamic_1_url', children=(
item('dynamic_1_sub_1', 'dynamic_1_sub_1_url'),
)),
item('dynamic_2', 'dynamic_2_url'),
)),
)),
reset_cache=True
)