当前位置: 首页>>代码示例>>Golang>>正文


Golang template.FuncMap函数代码示例

本文整理汇总了Golang中html/template.FuncMap函数的典型用法代码示例。如果您正苦于以下问题:Golang FuncMap函数的具体用法?Golang FuncMap怎么用?Golang FuncMap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了FuncMap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestTemplateFuncMap_join

func TestTemplateFuncMap_join(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{join .Arr .Sep}}`))
	var buf bytes.Buffer
	for _, v := range []struct {
		Arr    interface{}
		Sep    string
		expect string
	}{
		{[]int{1, 2, 3}, "&", "1&2&3"},
		{[2]uint{12, 34}, " and ", "12 and 34"},
		{[]string{"alice", "bob", "carol"}, ", ", "alice, bob, carol"},
		{[]string(nil), "|", ""},
		{[]bool{}, " or ", ""},
		{[]interface{}{"1", 2, "three", uint32(4)}, "-", "1-2-three-4"},
		{[]string{"あ", "い", "う", "え", "お"}, "_", "あ_い_う_え_お"},
		{[]string{"a", "b", "c"}, "∧", "a∧b∧c"},
	} {
		buf.Reset()
		if err := tmpl.Execute(&buf, v); err != nil {
			t.Error(err)
			continue
		}
		actual := buf.String()
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`{{join %#v %#v}} => %#v; want %#v`, v.Arr, v.Sep, actual, expect)
		}
	}
}
开发者ID:naoina,项目名称:kocha,代码行数:31,代码来源:template_test.go

示例2: NewTemplate

func NewTemplate() *template.Template {
	return template.New("").Funcs(template.FuncMap(map[string]interface{}{
		"q": func(fieldName string) (interface{}, error) {
			return nil, errors.New("The q template dummy function was called")
		},
	}))
}
开发者ID:ivartj,项目名称:norske-irc-kanaler.com,代码行数:7,代码来源:site.go

示例3: TestTemplate_FuncMap_url

func TestTemplate_FuncMap_url(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "root"}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %q, but %q", expected, actual)
		}
	}()

	func() {
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{url "user" 713}}`))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, nil); err != nil {
			panic(err)
		}
		actual := buf.String()
		expected := "/user/713"
		if !reflect.DeepEqual(actual, expected) {
			t.Errorf("Expect %v, but %v", expected, actual)
		}
	}()
}
开发者ID:naoina,项目名称:kocha,代码行数:30,代码来源:template_test.go

示例4: TemplatesFuncs

// TemplatesFuncs adds functions that will be available to all templates.
// It is legal to overwrite elements of the map.
func TemplatesFuncs(funcs FuncMap) {
	if templates == nil {
		panic(errNoTemplatesDir)
	}

	templates.Funcs(template.FuncMap(funcs))
}
开发者ID:volatile,项目名称:response,代码行数:9,代码来源:helper.go

示例5: TestTemplateFuncMap_flash

func TestTemplateFuncMap_flash(t *testing.T) {
	c := newTestContext("testctrlr", "")
	funcMap := template.FuncMap(c.App.Template.FuncMap)
	for _, v := range []struct {
		key    string
		expect string
	}{
		{"", ""},
		{"success", "test succeeded"},
		{"success", "test successful"},
		{"error", "test failed"},
		{"error", "test failure"},
	} {
		c.Flash = kocha.Flash{}
		c.Flash.Set(v.key, v.expect)
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(fmt.Sprintf(`{{flash . "unknown"}}{{flash . "%s"}}`, v.key)))
		var buf bytes.Buffer
		if err := tmpl.Execute(&buf, c); err != nil {
			t.Error(err)
			continue
		}
		actual := buf.String()
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`{{flash . %#v}} => %#v; want %#v`, v.key, actual, expect)
		}
	}
}
开发者ID:naoina,项目名称:kocha,代码行数:28,代码来源:template_test.go

示例6: BenchmarkBigGo

func BenchmarkBigGo(b *testing.B) {
	b.ReportAllocs()
	tmpl := template.New("")
	tmpl.Funcs(template.FuncMap{"t": func(s string) string { return s }})
	tmpl.Funcs(template.FuncMap(templateFuncs.asTemplateFuncMap()))
	readFile := func(name string) string {
		data, err := ioutil.ReadFile(filepath.Join("_testdata", name))
		if err != nil {
			b.Fatal(err)
		}
		return "{{ $Vars := .Vars }}\n" + string(data)
	}
	if _, err := tmpl.Parse(readFile("1.html")); err != nil {
		b.Fatal(err)
	}
	t2 := tmpl.New("2.html")
	if _, err := t2.Parse(readFile("2.html")); err != nil {
		b.Fatal(err)
	}
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err != nil {
		b.Fatal(err)
	}
	buf.Reset()
	b.ResetTimer()
	for ii := 0; ii < b.N; ii++ {
		tmpl.Execute(&buf, nil)
		buf.Reset()
	}
}
开发者ID:rainycape,项目名称:gondola,代码行数:30,代码来源:template_test.go

示例7: TestTemplate_FuncMap_in

func TestTemplate_FuncMap_in(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	var buf bytes.Buffer
	for _, v := range []struct {
		Arr    interface{}
		Sep    interface{}
		expect string
		err    error
	}{
		{[]string{"b", "a", "c"}, "a", "true", nil},
		{[]string{"ab", "b", "c"}, "a", "false", nil},
		{nil, "a", "", fmt.Errorf("valid types are slice, array and string, got `invalid'")},
	} {
		buf.Reset()
		tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{in .Arr .Sep}}`))
		err := tmpl.Execute(&buf, v)
		if !strings.HasSuffix(fmt.Sprint(err), fmt.Sprint(v.err)) {
			t.Errorf(`{{in %#v %#v}}; error has "%v"; want "%v"`, v.Arr, v.Sep, err, v.err)
		}
		actual := buf.String()
		expect := v.expect
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf(`{{in %#v %#v}} => %#v; want %#v`, v.Arr, v.Sep, actual, expect)
		}
	}
}
开发者ID:naoina,项目名称:kocha,代码行数:27,代码来源:template_test.go

示例8: NewHtml

// Creates HTML template with predefined functions
func NewHtml(name string) *template.Template {
	tmpl := template.New(name)

	extends := template.FuncMap(map[string]interface{}{
		"extends": func(name string, data interface{}) (html template.HTML, err error) {
			buf := bytes.NewBuffer([]byte{})

			if err = tmpl.ExecuteTemplate(buf, name, data); err == nil {
				html = template.HTML(buf.String())
			}

			return
		},
	})

	return tmpl.Funcs(template.FuncMap(coreFuncs)).Funcs(extends)
}
开发者ID:truszkowski,项目名称:gotemple,代码行数:18,代码来源:html.go

示例9: NewConf

func NewConf(name string, backends conf.EnabledBackends, text string) (c *Conf, err error) {
	defer errRecover(&err)
	c = &Conf{
		Name:             name,
		Vars:             make(map[string]string),
		Templates:        make(map[string]*conf.Template),
		Alerts:           make(map[string]*conf.Alert),
		Notifications:    make(map[string]*conf.Notification),
		RawText:          text,
		bodies:           htemplate.New(name).Funcs(htemplate.FuncMap(defaultFuncs)),
		subjects:         ttemplate.New(name).Funcs(defaultFuncs),
		Lookups:          make(map[string]*conf.Lookup),
		Macros:           make(map[string]*conf.Macro),
		writeLock:        make(chan bool, 1),
		deferredSections: make(map[string][]deferredSection),
		backends:         backends,
	}
	c.tree, err = parse.Parse(name, text)
	if err != nil {
		c.error(err)
	}
	saw := make(map[string]bool)
	for _, n := range c.tree.Root.Nodes {
		c.at(n)
		switch n := n.(type) {
		case *parse.PairNode:
			c.seen(n.Key.Text, saw)
			c.loadGlobal(n)
		case *parse.SectionNode:
			c.loadSection(n)
		default:
			c.errorf("unexpected parse node %s", n)
		}
	}

	loadSections := func(sectionType string) {
		for _, dSec := range c.deferredSections[sectionType] {
			c.at(dSec.SectionNode)
			dSec.LoadFunc(dSec.SectionNode)
		}
	}

	loadSections("template")
	if c.unknownTemplate != "" {
		t, ok := c.Templates[c.unknownTemplate]
		if !ok {
			c.errorf("template not found: %s", c.unknownTemplate)
		}
		c.UnknownTemplate = t
	}
	loadSections("notification")
	loadSections("macro")
	loadSections("lookup")
	loadSections("alert")

	c.genHash()
	return
}
开发者ID:nicollet,项目名称:bosun,代码行数:58,代码来源:rule.go

示例10: loadTemplate

func (c *Conf) loadTemplate(s *parse.SectionNode) {
	name := s.Name.Text
	if _, ok := c.Templates[name]; ok {
		c.errorf("duplicate template name: %s", name)
	}
	t := conf.Template{
		Vars: make(map[string]string),
		Name: name,
	}
	t.Text = s.RawText
	t.Locator = newSectionLocator(s)
	funcs := ttemplate.FuncMap{
		"V": func(v string) string {
			return c.Expand(v, t.Vars, false)
		},
	}
	saw := make(map[string]bool)
	for _, p := range s.Nodes.Nodes {
		c.at(p)
		switch p := p.(type) {
		case *parse.PairNode:
			c.seen(p.Key.Text, saw)
			v := p.Val.Text
			switch k := p.Key.Text; k {
			case "body":
				t.RawBody = v
				tmpl := c.bodies.New(name).Funcs(htemplate.FuncMap(funcs))
				_, err := tmpl.Parse(t.RawBody)
				if err != nil {
					c.error(err)
				}
				t.Body = tmpl
			case "subject":
				t.RawSubject = v
				tmpl := c.subjects.New(name).Funcs(funcs)
				_, err := tmpl.Parse(t.RawSubject)
				if err != nil {
					c.error(err)
				}
				t.Subject = tmpl
			default:
				if !strings.HasPrefix(k, "$") {
					c.errorf("unknown key %s", k)
				}
				t.Vars[k] = v
				t.Vars[k[1:]] = t.Vars[k]
			}
		default:
			c.errorf("unexpected node")
		}
	}
	c.at(s)
	if t.Body == nil && t.Subject == nil {
		c.errorf("neither body or subject specified")
	}
	c.Templates[name] = &t
}
开发者ID:nicollet,项目名称:bosun,代码行数:57,代码来源:rule.go

示例11: TestTemplate_FuncMap_in_withInvalidType

func TestTemplate_FuncMap_in_withInvalidType(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{in 1 1}}`))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err == nil {
		t.Errorf("Expect errors, but no errors")
	}
}
开发者ID:naoina,项目名称:kocha,代码行数:9,代码来源:template_test.go

示例12: MakeMixer

func MakeMixer(tpdir string, fMap map[string]interface{}) func(...string) *template.Template {
	return func(fileNames ...string) *template.Template {
		names := make([]string, len(fileNames))
		for i, val := range fileNames {
			names[i] = tpdir + val + ".html"
		}
		return template.Must(template.New("").Funcs(template.FuncMap(fMap)).ParseFiles(names...))
	}
}
开发者ID:sore0159,项目名称:golang-helpers,代码行数:9,代码来源:mixer.go

示例13: New

func New(name, text string) (c *Conf, err error) {
	defer errRecover(&err)
	c = &Conf{
		Name:             name,
		CheckFrequency:   time.Minute * 5,
		DefaultRunEvery:  1,
		HTTPListen:       ":8070",
		StateFile:        "bosun.state",
		LedisDir:         "ledis_data",
		LedisBindAddr:    "127.0.0.1:9565",
		MinGroupSize:     5,
		PingDuration:     time.Hour * 24,
		ResponseLimit:    1 << 20, // 1MB
		SearchSince:      opentsdb.Day * 3,
		TSDBVersion:      &opentsdb.Version2_1,
		UnknownThreshold: 5,
		Vars:             make(map[string]string),
		Templates:        make(map[string]*Template),
		Alerts:           make(map[string]*Alert),
		Notifications:    make(map[string]*Notification),
		RawText:          text,
		bodies:           htemplate.New(name).Funcs(htemplate.FuncMap(defaultFuncs)),
		subjects:         ttemplate.New(name).Funcs(defaultFuncs),
		Lookups:          make(map[string]*Lookup),
		Macros:           make(map[string]*Macro),
	}
	c.tree, err = parse.Parse(name, text)
	if err != nil {
		c.error(err)
	}
	saw := make(map[string]bool)
	for _, n := range c.tree.Root.Nodes {
		c.at(n)
		switch n := n.(type) {
		case *parse.PairNode:
			c.seen(n.Key.Text, saw)
			c.loadGlobal(n)
		case *parse.SectionNode:
			c.loadSection(n)
		default:
			c.errorf("unexpected parse node %s", n)
		}
	}
	if c.Hostname == "" {
		c.Hostname = c.HTTPListen
		if strings.HasPrefix(c.Hostname, ":") {
			h, err := os.Hostname()
			if err != nil {
				c.at(nil)
				c.error(err)
			}
			c.Hostname = h + c.Hostname
		}
	}
	return
}
开发者ID:Skyscanner,项目名称:bosun,代码行数:56,代码来源:conf.go

示例14: execute

// Loads localization, template functions and executes the template.
func (d *Display) execute(wr io.Writer, fileContents string) error {
	loc, err := display_model.LoadLocTempl(d.ctx.FileSys(), fileContents, d.ctx.User().Languages()) // TODO: think about errors here.
	if err != nil {
		return err
	}
	vctx := d.ctx.ViewContext()
	vctx.Publish("loc", loc)
	funcMap := template.FuncMap(builtins(d.ctx))
	t, err := template.New("tpl").Funcs(funcMap).Parse(fileContents)
	if err != nil {
		return err
	}
	return t.Execute(wr, vctx.Get()) // TODO: watch for errors in execution.
}
开发者ID:crufter,项目名称:nocrud,代码行数:15,代码来源:display.go

示例15: TestTemplate_FuncMap_nl2br

func TestTemplate_FuncMap_nl2br(t *testing.T) {
	app := kocha.NewTestApp()
	funcMap := template.FuncMap(app.Template.FuncMap)
	tmpl := template.Must(template.New("test").Funcs(funcMap).Parse(`{{nl2br "a\nb\nc\n"}}`))
	var buf bytes.Buffer
	if err := tmpl.Execute(&buf, nil); err != nil {
		panic(err)
	}
	actual := buf.String()
	expected := "a<br>b<br>c<br>"
	if !reflect.DeepEqual(actual, expected) {
		t.Errorf("Expect %q, but %q", expected, actual)
	}
}
开发者ID:naoina,项目名称:kocha,代码行数:14,代码来源:template_test.go


注:本文中的html/template.FuncMap函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。