如何执行HTML模板

huangapple go评论86阅读模式
英文:

How to execute the html template

问题

在这段代码中,我正在尝试执行showAbout()函数中的tmpl.ExecuteTemplate(res, "about.html", d)

handler.go文件中,我有两个函数。第一个是showAbout(),第二个是about()about()函数检查授权,在成功授权后,它会进入showAbout()函数,其中包含一个if语句。

如果数据库中的about字段为空,则应执行aboutform.html,获取数据并插入到数据库中。

如果成功插入数据,则显示消息并返回到about.html以显示数据。

只有about.html没有执行。尽管给出了成功消息。

about.html

<section>
   <h1>About</h1>
   <hr>
   <p>{{.Aboutdata}}</p>
</section>

aboutform.html

<form action="/about" method="POST">
    <section>
        <label>Content</label>
        <textarea name="content"></textarea>
        <div>
            <input type="submit" value="Submit">
        </div>
    </section>
</form>

db.go

func Insertdata(key, value string) bool {
	collection := Connect.Database("webApp3").Collection("data")
	filter := bson.M{"email": Account.Email, "password": Account.Password}
	update := bson.M{
		"$set": bson.M{
			key: value,
		},
	}
	_, err := collection.UpdateOne(context.TODO(), filter, update)
	return err == nil
}

handler.go

func showAbout(res http.ResponseWriter, req *http.Request) {
	d := struct{ Aboutdata string }{Aboutdata: database.Account.About}
	if d.Aboutdata == "" {
		tmpl.ExecuteTemplate(res, "aboutform.html", nil)
		content := req.FormValue("content")
		inserted := database.Insertdata("about", content)
		if inserted == true {
			fmt.Println("About is successfully inserted")
			tmpl.ExecuteTemplate(res, "about.html", d)   // 它没有执行about.html文件
		} else {
			fmt.Println("About is not inserted")
		}
	} else {
		tmpl.ExecuteTemplate(res, "about.html", d)    // 尽管这里执行了相同的文件
	}
}

func about(res http.ResponseWriter, req *http.Request) {
	session, _ := store.Get(req, "session-name")
	var authenticated interface{} = session.Values["authenticated"]
	if authenticated != nil {
		isAuthenticated := session.Values["authenticated"].(bool)
		if !isAuthenticated {
			tmpl.ExecuteTemplate(res, "login.html", nil)
			return
		}
		showAbout(res, req)
	} else {
		tmpl.ExecuteTemplate(res, "login.html", nil)
		return
	}
}
英文:

In this code, I am trying to execute the tmpl.ExecuteTemplate(res, &quot;about.html&quot;, d) that is present in the showAbout() function.

In the handler.go file, I have two functions. The first one is showAbout() and the second is about(). about() function check the authorization and after successful authorization, it goes to the showAbout() function in which it has if-statement.

If the about field is empty in the database then it should execute the aboutform.html, take the data and insert it in the database.

If the data is inserted successfully then show the message and go back to about.html to show the data there.

Only about.html is not executing. Although the success message is given.

about.html

&lt;section&gt;
   &lt;h1&gt;About&lt;/h1&gt;
   &lt;hr&gt;
   &lt;p&gt;{{.Aboutdata}}&lt;/p&gt;
&lt;/section&gt;

aboutform.html

&lt;form action=&quot;/about&quot; method=&quot;POST&quot;&gt;
    &lt;section&gt;
        &lt;label&gt;Content&lt;/label&gt;
        &lt;textarea name=&quot;content&quot;&gt;&lt;/textarea&gt;
        &lt;div&gt;
            &lt;input type=&quot;submit&quot; value=&quot;Submit&quot;&gt;
        &lt;/div&gt;
    &lt;/section&gt;
&lt;/form&gt;

db.go

func Insertdata(key, value string) bool {
	collection := Connect.Database(&quot;webApp3&quot;).Collection(&quot;data&quot;)
	filter := bson.M{&quot;email&quot;: Account.Email, &quot;password&quot;: Account.Password}
	update := bson.M{
		&quot;$set&quot;: bson.M{
			key: value,
		},
	}
	_, err := collection.UpdateOne(context.TODO(), filter, update)
	return err == nil
}

handler.go

func showAbout(res http.ResponseWriter, req *http.Request) {
	d := struct{ Aboutdata string }{Aboutdata: database.Account.About}
	if d.Aboutdata == &quot;&quot; {
		tmpl.ExecuteTemplate(res, &quot;aboutform.html&quot;, nil)
		content := req.FormValue(&quot;content&quot;)
		inserted := database.Insertdata(&quot;about&quot;, content)
		if inserted == true {
			fmt.Println(&quot;About is successfully inserted&quot;)
			tmpl.ExecuteTemplate(res, &quot;about.html&quot;, d)   // It is not executing the about.html file
		} else {
			fmt.Println(&quot;About is not inserted&quot;)
		}
	} else {
		tmpl.ExecuteTemplate(res, &quot;about.html&quot;, d)    // Although this same file is executing here.
	}
}

func about(res http.ResponseWriter, req *http.Request) {
	session, _ := store.Get(req, &quot;session-name&quot;)
	var authenticated interface{} = session.Values[&quot;authenticated&quot;]
	if authenticated != nil {
		isAuthenticated := session.Values[&quot;authenticated&quot;].(bool)
		if !isAuthenticated {
			tmpl.ExecuteTemplate(res, &quot;login.html&quot;, nil)
			return
		}
		showAbout(res, req)
	} else {
		tmpl.ExecuteTemplate(res, &quot;login.html&quot;, nil)
		return
	}
}

答案1

得分: 1

以下是您的关于处理程序的示例。请注意,该示例仅是处理GET和POST请求的通用结构的示例。根据我所看到的,您的问题中的代码包含一些其他逻辑错误,您仍然需要解决这些错误。

请注意,渲染模板和处理数据输入的逻辑在GET和POST HTTP方法之间进行了分割。某些路由器允许基于方法的处理程序注册,在这种情况下,您可以有两个单独的处理程序,一个用于showAbout,另一个用于createAbout或其他操作。

在此示例中,使用return语句是不必要的,因为if-else块的结构已经足够,但是,我仍然包含它们,以明确说明,通常情况下,在您写入响应后,不应该有任何其他的响应写入代码:不要有http.Redirect,不要有更多的ExecuteTemplate调用等。

func handleAbout(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
         if data_is_present {
             if err := t.ExecuteTemplate(w, "about.html", nil); err != nil {
                 fmt.Println(err)
             }
             return
         } else if data_is_NOT_present {
             if err := t.ExecuteTemplate(w, "aboutform.html", nil); err != nil {
                 fmt.Println(err)
             }
             return
         }
    } else if r.Method == "POST" {
        content := r.FormValue("content")
        inserted := database.Insertdata("about", content)
        if inserted == true {
            d := struct{ Aboutdata string }{Aboutdata: content}
            if err := t.ExecuteTemplate(w, "about.html", d); err != nil {
                fmt.Println(err)
            }
            return
        } else {
            fmt.Println("About is not inserted")
            return
        }
    }
}

希望对您有所帮助!

英文:

Here's an example of how your about handler may look like. Keep in mind that the example is just an illustration of a generic structure for handling GET and POST request's with a single handler. From what I can tell the code in your question contains a number of other logical errors that you'll still have to resolve.

Notice that the logic of rendering the template and handling data input is split between the GET and POST HTTP methods. Some routers allow for method-based handler registering in which case you could have two separate handlers, one for showAbout and another for createAbout or something.

The use of return statements in this example is unnecessary given how the if-else blocks are structured, however, I did include them anyway to explicitly illustrate that, in general, after you write to the response once you should not have any other response-writing code: no http.Redirect, no more ExecuteTemplate calls, etc.

func handleAbout(w http.ResponseWriter, r *http.Request) {
    if r.Method == &quot;GET&quot; {
         if data_is_present {
             if err := t.ExecuteTemplate(w, &quot;about.html&quot;, nil); err != nil {
                 fmt.Println(err)
             }
             return
         } else if data_is_NOT_present {
             if err := t.ExecuteTemplate(w, &quot;aboutform.html&quot;, nil); err != nil {
                 fmt.Println(err)
             }
             return
         }
    } else if r.Method == &quot;POST&quot; {
        content := r.FormValue(&quot;content&quot;)
        inserted := database.Insertdata(&quot;about&quot;, content)
        if inserted == true {
            d := struct{ Aboutdata string }{Aboutdata: content}
            if err := t.ExecuteTemplate(w, &quot;about.html&quot;, d); err != nil {
                fmt.Println(err)
            }
            return
        } else {
            fmt.Println(&quot;About is not inserted&quot;)
            return
        }
    }
}

huangapple
  • 本文由 发表于 2021年8月9日 18:14:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/68710368.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定