Using slot and block tags
-
First let's clarify how
includeandextendstags work inside components.When component template includes
includeorextendstags, it's as if the "included" template was inlined. So if the "included" template containsslottags, then the component uses those slots.If you have a template
abc.html:And components that make use of
abc.htmlviaincludeorextends:from django_components import Component, register @register("my_comp_extends") class MyCompWithExtends(Component): template = """{% extends "abc.html" %}""" @register("my_comp_include") class MyCompWithInclude(Component): template = """{% include "abc.html" %}"""Then you can set slot fill for the slot imported via
include/extends:And it will render:
-
Slot and block
If you have a template
abc.htmllike so:and component
my_comp:Then:
-
Since the
blockwasn't overriden, you can use thebodyslot:And we get:
-
blocksCANNOT be overriden through thecomponenttag, so something like this:{% component "my_comp" %} {% fill "body" %} XYZ {% endfill %} {% endcomponent %} {% block "inner" %} 456 {% endblock %}Will still render the component content just the same:
-
You CAN override the
blocktags ofabc.htmlif the component template usesextends. In that case, just as you would expect, theblock innerinsideabc.htmlwill renderOVERRIDEN: -
This is where it gets interesting (but still intuitive). You can insert even new
slotsinside these "overriding" blocks:@register("my_comp") class MyComp(Component): template = """ {% extends "abc.html" %} {% load component_tags %} {% block "inner" %} OVERRIDEN {% slot "new_slot" %} hello {% endslot %} {% endblock %} """And you can then pass fill for this
new_slotwhen rendering the component:NOTE: Currently you can supply fills for both
new_slotandbodyslots, and you will not get an error for an invalid/unknown slot name. But sincebodyslot is not rendered, it just won't do anything. So this renders the same as above:
-