Templates for ease of maintenance

In the last example, there were some code duplication. Each and every page has the same navigation links as well as a header and a footer. If we want to edit the links, we will have to go through each and every file and edit them. Doing manual changes to different files is fraught with errors. Although for now this looks trivial because our files are small, things can get more complicated as we add more files and the files become bigger.

To reduce code duplication and errors in maintenance, Diet templates provide a mechanism using inheritance with the keyword extends.

Go to File→Save As... and save views\notsimplehello.dt as views\mainlayout.dt.

Edit views\mainlayout.dt to make it look like this:

html
  head
    title Demo site
  body
    header
      h2 Welcome to our not so simple site
    nav
      ul
        li <a href="/">Home</a>
        li <a href="/about">About us</a>
        li <a href="/events">Events</a>
        li <a href="/contact">Contact us</a>
        li <a href="/helloagain">Hello again!</a>
    article
      block content
    footer
      p Copyright 2022 Notsosimple Company

Then rename views\notsimplehello.dt into views\index.dt with this contents:

Edit views\about.dt with the following contents:

Edit views\events.dt with the following contents:

Edit views\contact.dt with the following contents:

Next, edit source\app.d to make it look like this:

Compile and run and refresh your browser. If you find that nothing has changed in the browser, you did good.

By creating a layout template, we placed the repeating tags in the layout template (which we called mainlayout.dt) while leaving the other templates with only their specific contents. We named the part that changes as the content block and we indicated in the other pages that their contents will appear in that content block of the mother layout.

In the block content statement, we have named that part, or ‘block’, of the layout as ‘content’. You can give the block any name as long as you give the same name to the other templates that inherit from that template.

Last updated