Home
Go
html template Example
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2024 (edit).
Home
Changes
© 2007-2024 Sam Allen.