In Go, the html/template package provides a robust framework for generating secure HTML output. This package automatically escapes inserted data appropriately to prevent cross-site scripting (XSS) attacks. The following are the basic steps to use this package:
1. Import the Package
First, import the html/template package.
goimport ( "html/template" "os" )
2. Define the Template
Templates can be defined directly as strings or stored in a file. The {{}} syntax in templates is used to bind data.
Define the template as a string:
goconst tpl = `\n<html>\n<head><title>{{.Title}}</title></head>\n<body>\n<h1>{{.Heading}}</h1>\n<p>{{.Content}}</p>\n</body>\n</html>\n`\n``` **Or, load the template from a file:** Assume there is a file named `template.html`: ```html\n<html>\n<head><title>{{.Title}}</title></head>\n<body>\n<h1>{{.Heading}}</h1>\n<p>{{.Content}}</p>\n</body>\n</html>\n``` ### 3. Parse the Template Use `template.New` to create a template and then use the `Parse` method to parse the defined template string. ```go\ntmpl, err := template.New("webpage").Parse(tpl)\nif err != nil {\n panic(err)\n}\n``` Or, if the template is stored in a file: ```go\ntmpl, err := template.ParseFiles("template.html")\nif err != nil {\n panic(err)\n}\n``` ### 4. Define Data Define a struct to represent the data to be used in the template. ```go\ntype PageData struct {\n Title string\n Heading string\n Content string\n}\n``` ### 5. Execute the Template Create an instance of `PageData` and fill it with data, then execute the template. ```go\ndata := PageData{\n Title: "My Webpage",\n Heading: "Welcome to my webpage",\n Content: "Here is some introductory information.",\n}\n\nerr = tmpl.Execute(os.Stdout, data)\nif err != nil {\n panic(err)\n}\n``` This code combines the template and data, outputting to `os.Stdout`. You can also replace it with any `io.Writer`, such as a file or buffer. ### Example Application Suppose we are developing a simple website that needs to display content for different pages. Using the above steps, we can easily create different templates for each page by simply changing the content in `PageData`, reusing the template to generate multiple pages. This approach makes the code more modular and reusable while maintaining output security.
2024年8月7日 17:58 回复