在golang html模板中访问{{range。}}作用域之外的结构变量 [英] Accessing struct variable outside of {{range .}} scope in golang html template
本文介绍了在golang html模板中访问{{range。}}作用域之外的结构变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
</head>
<body>
<div>
<h2>Reply</h2>
<form action="/post/{{$threadID}}" method="POST">
<input type="text" name="subject" />
<input type="text" name="name" value="Anonymous" />
<input type="text" name="message" />
<input type="submit" value="submit" />
</form>
</div>
<div>
{{range .}}
{{$threadID := .ThreadID}}
<h3>{{.Subject}}</h3>
<h3>{{.Name}}</h3>
<div>{{.DatePosted}}</div>
<div><p>{{.Text}}</p></div>
<br /><br />
{{end}}
</div>
</body>
我有这个模板,是页面顶部的一个表单,它要求发送的任何一个帖子的线程ID(它们都是相同的,是具有特定线程ID的所有帖子的一部分),这显然不起作用,我唯一的其他想法是沿着
I have this template, there is a form at the top of the page that requires the threadID from ANY one of the Posts sent (they're all the same, a slice of all posts with a certain threadID), this obviously doesn't work, my only other idea was something along the lines of
{{range .}}
{{if $threadID == nil}}
$threadID := .ThreadID
//build the form same as above
{{end}}
<h3>{{.Subject}}</h3>
<h3>{{.Name}}</h3>
<div>{{.DatePosted}}</div>
<div><p>{{.Text}}</p></div>
<br /><br />
{{end}}
以下是Post结构和方法
Here is the Post structure and methods if any of the above is unclear.
type Post struct {
threadID int
subject string
name string
text string
date_posted string
}
func (p *Post) ThreadID() int { return p.threadID }
func (p *Post) Subject() string { return p.subject }
func (p *Post) Name() string { return p.name }
func (p *Post) Text() string { return p.text }
func (p *Post) DatePosted() string { return p.date_posted }
发送到模板的帖子片段的来源
And the origin of the slice of posts sent to the template
threadID := r.URL.Path[len("/reply/"):]
replies, err := i.db.Query("SELECT * FROM latest_threads where thread_id="+threadID);
推荐答案
layoutData := struct {
ThreadID int
Posts []Post
} {
ThreadID: threadID,
Posts: Posts,
}
然后像这样的东西将工作
Then something like this will work
<!DOCTYPE html>
<html>
<head>
<title> Test </title>
</head>
<body>
<div>
<h2>Reply</h2>
<form action="/post/{{ .ThreadID }}" method="POST">
<input type="text" name="subject" />
<input type="text" name="name" value="Anonymous" />
<input type="text" name="message" />
<input type="submit" value="submit" />
</form>
</div>
<div>
{{range $post := .Posts}}
<h3>{{ $post.Subject}}</h3>
<h3>{{$post.Name}}</h3>
<div>{{$post.DatePosted}}</div>
<div><p>{{$post.Text}}</p></div>
<br /><br />
{{end}}
</div>
</body>
这篇关于在golang html模板中访问{{range。}}作用域之外的结构变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文