英文:
Run a function on data in a go html/template
问题
我想在Go模板中的字符串中添加连字符(-),当有人尝试保存时。我正在使用来自Go Wiki教程的一些修改后的代码,链接在这里:https://golang.org/doc/articles/wiki/
代码:
<h1>编辑 {{.Title}}</h1>                                                            
<form action="/save/{{.Title}}" method="POST">                                         
  <div><input name="title" type="text" placeholder="title"></div>                      
  <div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
  <div><input type="submit" value="Save"></div>                                        
</form>                                                                              
与以下代码行相关:
<form action="/save/{{.Title}}" method="POST">
我需要将.Title转换为类似"the quick brown fox"的内容转换为"the-quick-brown-fox"。
如上所示的代码,你可以添加一个类似println的函数,但我不确定如何在我的情况下实现这一点。
英文:
I want to add hyphens (-) to a string in a go template when someone tries to save it. I'm using some modified code from the go wiki tutorial here: https://golang.org/doc/articles/wiki/
Code:
<h1>Editing {{.Title}}</h1>                                                            
<form action="/save/{{.Title}}" method="POST">                                         
  <div><input name="title" type="text" placeholder="title"></div>                      
  <div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body}}</textarea></div>
  <div><input type="submit" value="Save"></div>                                        
</form>                                                                          
The line with
<form action="/save/{{.Title}}" method="POST">
is the relevant line. I need to transform .Title which might be something like "the quick brown fox" to "the-quick-brown-fox".
As you can see in the code above, you can add a function like println, but I'm not sure how I would do this for my case.
答案1
得分: 2
你可以将template.FuncMap传递给模板,然后可以这样做:
{{ .Title | title }}
https://play.golang.org/p/KWy_KRttD_
func Sluggify(s string) string {
    return strings.ToLower(s) //例如
}
func main() {
    funcMap := template.FuncMap {
        "title": Sluggify,
    }
    tpl := template.Must(template.New("main").Funcs(funcMap).Parse(`{{define "T"}}Hello {{.Title | title }} Content: {{.Content}}{{end}}`))
    tplVars := map[string]string {
        "Title": "Hello world",
        "Content": "Hi there",
    }
    tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
}
英文:
You can pass a template.FuncMap to the template and then you can do something like:
{{ .Title | title }}
https://play.golang.org/p/KWy_KRttD_
func Sluggify(s string) string {
    return strings.ToLower(s) //for example
}
func main() {
    funcMap := template.FuncMap {
        "title": Sluggify,
    }
    tpl := template.Must(template.New("main").Funcs(funcMap).Parse(`{{define "T"}}Hello {{.Title | title }} Content: {{.Content}}{{end}}`))
    tplVars := map[string]string {
        "Title": "Hello world",
        "Content": "Hi there",
    }
    tpl.ExecuteTemplate(os.Stdout, "T", tplVars)
}
答案2
得分: 1
你的所有*Page结构体都是由loadPage函数创建的。所以最简单的方法似乎是在那时创建你的连字符标题并将其存储在你的page结构体中:
type Page struct {
    Title       string
    HyphenTitle string
    Body        []byte
}
func loadPage(title string) (*Page, error) {
    filename := title + ".txt"
    body, err := ioutil.ReadFile(filename)
    if err != nil {
        return nil, err
    }
    return &Page{Title: title, Body: body, HyphenTitle: hyphenate(title)}, nil
}
func hyphenate(s string) string {
    return strings.Replace(s, " ", "-", -1)
}
然后在需要的地方使用{{.HyphenTitle}}。
英文:
All of your *Page structs are created by the loadPage function. So it would seem to be easiest to just create your hyphenated title then and store it in your page struct:
type Page struct {
	Title string
    HyphenTitle string
	Body  []byte
}
func loadPage(title string) (*Page, error) {
	filename := title + ".txt"
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &Page{Title: title, Body: body, HyphenTitle: hyphenate(title)}, nil
}
func hyphenate (s string) string {
    return strings.Replace(s," ","-",-1)
}
Then just use {{.HyphenTitle}} where you want it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论