Use Golang's standard library to build a website--2. Template parsing

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Parsing of templates

Since it's a website,

fmt.Fprintf"Hello world, this is my first page!")

This way must not be used, you have to parse the template.
The package used for template parsing is "Html/template", the pilot package, and then the index function is overwritten:

//先导入html/template包import"html/template"func Index(w http.ResponseWriter, r *http.Request) {    //解析指定模板文件index.html    t, _ := template.ParseFiles("index.html")    //输出到浏览器    nil)}

In preparing an HTML file, as follows:

<HTML>    <head>        <title>            这是一个测试文件        </title>    </head>    <body>        <p>            Hello world, this is my first page!        </p>    </body></HTML>

Run it and get the same results as above.

Then insert the data into the template, which is easy:

func Index(w http.ResponseWriter, r *http.Request) {    //用于保存数据的map    make(map[string]string)    t, _ := template.ParseFiles("index.html")    data["Name""BCL"    t.Execute(w, data)}

Insert a new tag in the HTML file:

<p> Hello , {{.Name}} </p>

So you can parse the template properly.

Let's take a quick look at the syntax of the Go language template

To be continued .....

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.