Parts & Pages#

How do I override part of a part/page?#

This is all just standard tri.declarative magic, but as you are likely new to it this might take a while to get used to. Let’s say you created yourself a master template for your site.

class BasePage(Page):
    title = html.h1('My awesome webpage')
    subtitle = html.h2('It rocks')
▼ Hide result

Which you can use like this:

def index(request):
    class IndexPage(BasePage):
        body = 'body'
    return IndexPage(parts__subtitle__children__child='Still rocking...')
▼ Hide result

Here you can see that Part s (Page s are themselves Part s) form a tree and the direct children are gathered in the parts namespace. Here we overwrote a leaf of an existing namespace, but you can also add new elements or replace bigger parts (and most of the time it doesn’t matter if you use the class Meta or the keyword arguments to init syntax):

def index(request):
    class IndexPage(BasePage):
        title = html.img(
            attrs=dict(
                src='https://docs.iommi.rocks/en/latest/_static/logo_with_outline.svg',
                alt='iommi logo',
                width='70px',
            ),
        )
    return IndexPage(parts__subtitle=None)
▼ Hide result

In the above we replaced the title and removed the subtitle element completely. The latter of which shows one of the gotchas as only str, Part and the django template types are gathered into the parts structure when a Part class definition is processed. As None is not an instance of those types, you can remove things by setting their value to None.

How do I set the title of my page?#

As in the text shown in the browser status bar?

Page(title='The title in the browser')

Note that this is different from

class MyPage(Page):
    title = Header('A header element in the dom')

MyPage()

Which is equivalent to:

Page(parts__title=Header('A header element in the dom'))

How do I specify the context used when a Template is rendered?#

def index(request):
    context = {'today': date.today()}

    class MyPage(Page):
        body = Template("""A django template was rendered on {{today}}.""")

    return MyPage(context=context)
▼ Hide result

You can also insert items in the context via the declaration. This not only makes the above shorter, but also makes it easy to write abstractions that can be extended later:

Page(
    parts__body=Template("""A django template was rendered on {{today}}."""),
    context__today=date.today(),
)
▼ Hide result