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 <ahref="/">Home</a> li <ahref="/about">About us</a> li <ahref="/events">Events</a> li <ahref="/contact">Contact us</a> li <ahref="/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.
extends mainlayout
block content
hl Welcome to our not so simple site!
div.
Lorem ipsum dolor sit amet, consectetur adipisci elit, sed
eiusmod tempor incidunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrum exercitationem ullam
corporis suscipit laboriosam, nisi ut aliquid ex ea commodi
consequatur. Quis aute iure reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
obcaecat cupiditat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
extends mainlayout
block content
h1 This is the About us page
extends mainlayout
block content
h1 This is the Events page
extends mainlayout
block content
h1 This is the Contact us page!