Monday, November 11, 2013

Creating a "Master Page" for your Go Web App

Most web apps share a common layout across different views. This common layout may include a header or a footer and even a navigation menu. Go's batteries-included standard library provides an easy way to create these common elements that can be reused in different views to create a "Master Page"-like effect.

This basic example demonstrates how:

Let's create a simple web app that has 2 views - a Main view and an About view. Both these views have the same header and footer sections.

The header template is defined in a file named header.html

The footer template is defined in a file named footer.html

The Main template is defined in a file named main.html

The About template is defined in a file name about.html

And here's the code that serves it up.

Each of the above templates has a name defined using the {{define "name"}} action. The Main and About templates include the header and footer templates using the {{template "name" .}} action. The '.' passes in the context to the named template. Now whenever the Main and About templates are executed, the header and footer will get included and inserted at the required location. That's all there is to it.

This is how the 2 views look.


This technique can also be used to create different layouts for different sections of the web app; for example, the administration section may look different from the user section. We just need to name our templates appropriately and include them where required.

No comments:

Post a Comment