Computer Magic Logo
Master Templates

Wednesday, June 24, 2015

Published by Aristotelis Pitaridis

Almost all the web sites have pages with common parts of HTML. For example if we want all the pages of a web site to have the same header, menu and footer, It would not be a good idea to add multiple times the same HTML for each of these pages. In case that we do such a thing and we want to change something in the header, then we will have to go to all pages and make the same change multiple times. This needs a lot of work and there is a possibility to make a mistake in one of the pages. Let’s go and create a Master Template for the HomePage page so that we will see how easy it is to have Master Templates in our web site.

We right click on the Templates node of the Settings section and a list of commands will appear on the screen.

We click on the Create command and a form will appear in order to type the name of the template.

We type the name MasterTemplate and we click the Create button. The new template will appear on the screen and the contents of the template will appear on the template editor.

We change the contents of our MasterTemplate and we add the same contents that we have in our HomePage. The only change is that we remove the body content property and we replace it with the @RenderBody() command. This asks from the system to give the part of the page which is defined by the template which uses the Master Template. This means that in the MasterTemplate we have added all the contents which will be the same in each of our pages. When we change the contents of the MasterTemplate we click the Save button which is located on the upper right corner of the browser in order to save the changes.

Now we select the HomePage template and we change its contents so that the only HTML that we will have will be the one for displaying the Page Contents property. We also have to change a line of the C# code. Initially the Layout variable was set to be equal to null. Now we have to change its value so that it will contains the name of the MasterTemplate.

Our site now has a Master Template and if we create new templates which will have as Layout the MasterTemplate that we created, they will all contain the same structure and they will be able to alter only the variable part of each page.