Home
Go
html template Example
Updated Sep 25, 2024
Dot Net Perls
HTML template. Websites are under nearly constant attack. Most of these are automated. To prevent a certain kind of attack, a special Go module called "html/template" is available.
With this module, we pass HTML markup to a Parse() method. Then when we call Execute(), we insert values into special substitutions. Characters are escaped.
An example program. We must use a Writer with the "html/template" package. This program uses the bufio package to create a Writer (with NewWriter).
File
And Once the Writer is created, we can create a new template with template.New. We provide a name for the template ("example").
Info We call this func and pass a specially-formatted string. The substitution comes after the word "Hello" here.
Finally We call Execute. We pass the Writer, followed by the values to be inserted into the HTML template.
package main import ( "bufio" "html/template" "os" ) func main() { // Create a file. f, _ := os.Create("file.txt") // New writer. out := bufio.NewWriter(f) // Create template and parse it. t, _ := template.New("example").Parse("<p>Hello {{.}}</p>") // Insert string into substitution. t.Execute(out, "Friend") // Done. out.Flush() }
<p>Hello Friend</p>
Notes, result of program. To see the result of the program, open the file it wrote to—you will want to adjust the path before you execute the program.
Notes, continued. The HTML is fully generated. The string "Friend" was placed in the HTML where the substitution marker was originally present.
A review. Generating HTML is (for the most part) not an interesting problem. But it is a useful thing to do—HTML is perhaps the most widely used document format in the world.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 25, 2024 (edit).
Home
Changes
© 2007-2025 Sam Allen