HTML Templating With Go
When you’re building a website, you’ll typically generate some of your final content dynamically. You’ll then want to inject that data into your final web pages for display in a browser.
You can take one of two approaches: embed your page structure into your program, or combine your final data with separate template files.

Templating provides separation of concerns for a more maintainable codebase. It also makes it easier to split front-end tasks and back-end tasks, allocating them to different team members. Go has excellent templating support in its standard library.
Getting Started With Templating in Go
Go has two templating packages in the standard library:text/templateandhtml/template. The text/template package has functionality for parsing text files, while html/template handles HTML. By using the html/template you’re secured from cross-site scripting (XSS) attacks since Go escapes data entry during rendering. This is another advantage of templating over a manual approach.
Since the template package is part of the standard library, you won’t need to install any dependencies; just import it:

Start bycreating an HTML fileto use as a template for your application. You can use the standard.htmlextension or either.gohtmlor.tmpl, both are which are also common. Whatever extension you use, the functionality within your application will be the same. Some text editors may apply different syntax highlighting depending on your templates’ extensions. Here’s a basic skeleton:
Save this file in your Go program’s directory. you’re able to now start to work with it, as a template, within your program.

Create a global instance of theTemplatemethod of the template package. You’ll access this template instance from various parts of your program.
You’ll have to create a simple server to render and display your templates. Here’s how to start a simple server in Go using thenet/httppackage:

You’ll call therunServerfunction from your main function to start the server. The server has only one route, the/homeroute, which will display your page. ThehandlePageparameter is the name of a handler function that will render your page. TheListenAndServemethod starts the server listening on port8080onlocalhost, i.e. your own computer.
Passing Variables to Templates
Create a global struct namedNews:
You’ll use this struct to store data and pass it to your template for display on your final page. In your template, you can then use this syntax to inject data:

Wherenameis the name of a variable you have passed to your template. When you render the template, it will replace values in braces with corresponding data from your Go code. Since the following example will pass a struct, you’ll use dot notation to access its fields:
Replace the empty body element in your template’s skeleton markup with the code above.
ThehandlePagehandler function will verify that the request for the page is a GET request. It then populates a struct with sample data before rendering the template and serving the final page:
TheParseFilesmethod parses the HTML file you specify. Theeventvariable is the initialized struct. TheExecutemethod will inject the supplied data into the final page, according to the placeholders in the template. Execute takes aResponseWriterand the data, in this case, the struct.
Here’s the result from running the server and visiting the page:
Using Control Structures in Templates
you’re able to also use control structures like conditional statements, and loops in your templates.
A loop allows you to output several values and reuse the same structure for each. Use therangekeyword to define the beginning of the repeated content and theendkeyword for the end. Within the loop you can use the{{.}}syntax to inject the current value:
Then you’ll pass the name of the data structure you want to loop through as a parameter to the Execute method:
ThemakeUseOfCategoriesvariable is a slice of strings to pass as the data parameter. Here’s the result of looping through the slice:
You can use a conditional statement in your templates to test the value of a boolean variable. Create a struct with boolean fields, like this:
To use a conditional, include theifkeyword in double braces before the name of the variable to test. End the conditional block with theendkeyword in braces:
Initializing a struct in Go sets the values to false on default, so if you do not initialize a field, it evaluates to false. On initializing the struct and passing the variable as the data to the template, only the fields that evaluate to true cause output to appear.
The final output includes just a single paragraph since only the isTrue field evaluates to true:
You Don’t Have to Use Templates for Your Backend Applications
Templating isn’t a requirement for your Go apps. You can use other approaches like embedding your page structure into your program, alongside its logic and other behavior.
However, you’ll end up making more work for yourself. Go templating helps prevent XSS attacks and makes it easier to separate work on page structure from backend logic.
With a simple database abstraction package, using SQL from Go is easier than you might think.
Your phone’s camera app doesn’t show this, so it’s easy to miss.
Now, I actually finish the books I start.
Revolutionize your driving experience with these game-changing CarPlay additions.
The best features aren’t the ones being advertised.
Don’t let someone else take over your phone number.