在Go的html/template中运行一个函数来处理数据。

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

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:

&lt;h1&gt;Editing {{.Title}}&lt;/h1&gt;                                                            
&lt;form action=&quot;/save/{{.Title}}&quot; method=&quot;POST&quot;&gt;                                         
  &lt;div&gt;&lt;input name=&quot;title&quot; type=&quot;text&quot; placeholder=&quot;title&quot;&gt;&lt;/div&gt;                      
  &lt;div&gt;&lt;textarea name=&quot;body&quot; rows=&quot;20&quot; cols=&quot;80&quot;&gt;{{printf &quot;%s&quot; .Body}}&lt;/textarea&gt;&lt;/div&gt;
  &lt;div&gt;&lt;input type=&quot;submit&quot; value=&quot;Save&quot;&gt;&lt;/div&gt;                                        
&lt;/form&gt;                                                                          

The line with

&lt;form action=&quot;/save/{{.Title}}&quot; method=&quot;POST&quot;&gt;

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 {
        &quot;title&quot;: Sluggify,
    }

    tpl := template.Must(template.New(&quot;main&quot;).Funcs(funcMap).Parse(`{{define &quot;T&quot;}}Hello {{.Title | title }} Content: {{.Content}}{{end}}`))
    tplVars := map[string]string {
        &quot;Title&quot;: &quot;Hello world&quot;,
        &quot;Content&quot;: &quot;Hi there&quot;,
    }
    tpl.ExecuteTemplate(os.Stdout, &quot;T&quot;, 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 + &quot;.txt&quot;
	body, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return &amp;Page{Title: title, Body: body, HyphenTitle: hyphenate(title)}, nil
}

func hyphenate (s string) string {
    return strings.Replace(s,&quot; &quot;,&quot;-&quot;,-1)
}

Then just use {{.HyphenTitle}} where you want it.

huangapple
  • 本文由 发表于 2017年1月28日 06:59:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/41904390.html
匿名

发表评论

匿名网友

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

确定