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


Golang template.FuncMap函数代码示例

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


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

示例1: Run

func Run(uni *context.Uni, commands string) (string, error) {
	if !scut.IsAdmin(uni.Dat["_user"]) {
		return "", fmt.Errorf("Currently only admins can use this.")
	}
	lines := strings.Split(commands, "\n")
	for i, v := range lines {
		// This hack...
		if len(v) > 0 && v[0] != '#' {
			lines[i] = "{{" + v + "}}"
		}
	}
	whole_file := strings.Join(lines, "\n")
	funcMap := template.FuncMap(builtins(uni))
	t, err := template.New("shell").Funcs(funcMap).Parse(string(whole_file))
	if err != nil {
		return "", strip(err)
	}
	context := map[string]interface{}{"dat": uni.Dat, "opt": uni.Opt}
	var buffer bytes.Buffer
	err = t.Execute(&buffer, context) // TODO: watch for errors in execution.
	if err != nil {
		return "", strip(err)
	}
	output_lines := strings.Split(buffer.String(), "\n")
	output_lines = stripComments(output_lines)
	return strings.Join(output_lines, "\n"), nil
}
开发者ID:Laller,项目名称:hypecms,代码行数:27,代码来源:shell.go

示例2: main

func main() {
	tpl := template.New(flag.Arg(0))
	tpl.Funcs(template.FuncMap(map[string]interface{}{
		"string": func(filename string) (string, error) {
			buf, err := ioutil.ReadFile(filename)
			if err != nil {
				return "", err
			}

			return strconv.Quote(string(buf)), nil
		},
		"bytes": func(filename string) (string, error) {
			buf, err := ioutil.ReadFile(filename)
			if err != nil {
				return "", err
			}

			return fmt.Sprintf("%#v", buf), nil
		},
	}))
	_, err := tpl.ParseFiles(flag.Arg(0))
	catch(err)

	file, err := os.Create(regexp.MustCompile("\\.got$").ReplaceAllString(flag.Arg(0), "") + ".go")
	catch(err)
	defer file.Close()

	err = tpl.Execute(file, nil)
	catch(err)
}
开发者ID:hjr265,项目名称:goatee,代码行数:30,代码来源:goatee.go

示例3: NewText

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

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

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

			return
		},
	})

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

示例4: loadEmail

func loadEmail() {
	contents, _ := ioutil.ReadDir("tmpl/email")
	templatePaths := make([]string, 0)
	for _, fileInfo := range contents {
		if fileInfo.Mode().IsRegular() && strings.HasSuffix(fileInfo.Name(), ".txt") {
			templatePaths = append(templatePaths, "tmpl/email/"+fileInfo.Name())
		}
	}
	emailTemplate = template.Must(template.New("").Funcs(template.FuncMap(templateFuncMap())).ParseFiles(templatePaths...))
}
开发者ID:carriercomm,项目名称:lobster,代码行数:10,代码来源:email.go

示例5: Funcs

// Funcs returns the functions that can be used for interpolation given
// a context.
func Funcs(ctx *Context) template.FuncMap {
	result := make(map[string]interface{})
	for k, v := range FuncGens {
		result[k] = v(ctx)
	}
	if ctx != nil {
		for k, v := range ctx.Funcs {
			result[k] = v
		}
	}

	return template.FuncMap(result)
}
开发者ID:henrysher,项目名称:packer,代码行数:15,代码来源:funcs.go

示例6: main

func main() {

	settings := evergreen.GetSettingsOrExit()
	home := evergreen.FindEvergreenHome()
	uis, err := ui.New(settings, home)
	if err != nil {
		fmt.Println("Failed to create ui server: %v", err)
		os.Exit(1)
	}
	router, err := uis.NewRouter()
	if err != nil {
		fmt.Println("Failed to create router:", err)
		os.Exit(1)
	}

	webHome := filepath.Join(uis.Home, "public")

	functionOptions := ui.FuncOptions{webHome, uis.Settings.Ui.HelpUrl, true, router}

	functions, err := ui.MakeTemplateFuncs(functionOptions, uis.Settings.SuperUsers)
	htmlFunctions := htmlTemplate.FuncMap(functions)
	textFunctions := textTemplate.FuncMap(functions)

	if err != nil {
		fmt.Println("Failed to create template function map:", err)
		os.Exit(1)
	}

	uis.Render = render.New(render.Options{
		Directory:    filepath.Join(uis.Home, ui.WebRootPath, ui.Templates),
		DisableCache: !uis.Settings.Ui.CacheTemplates,
		HtmlFuncs:    htmlFunctions,
		TextFuncs:    textFunctions,
	})
	err = uis.InitPlugins()
	if err != nil {
		fmt.Println("WARNING: Error initializing plugins:", err)
	}

	n := negroni.New()
	n.Use(negroni.NewStatic(http.Dir(webHome)))
	n.Use(ui.NewLogger())
	n.Use(negroni.HandlerFunc(ui.UserMiddleware(uis.UserManager)))
	n.UseHandler(router)
	graceful.Run(uis.Settings.Ui.HttpListenAddr, requestTimeout, n)
	evergreen.Logger.Logf(slogger.INFO, "UI server cleanly terminated")
}
开发者ID:tychoish,项目名称:evergreen,代码行数:47,代码来源:ui.go

示例7: Publish

func (this *SunnyPublisher) Publish(wr io.Writer, name string, data interface{}) {
	// TODO: use sync.Pool instead once GAE supports 1.3

	// get cloned template from pool
	// add contextual funcmap to the template

	if strings.HasSuffix(name, ".html") {
		ht, err := this.htmpl.Clone()
		ht.Funcs(htemplate.FuncMap(this.fmap))

		if err == nil {
			ht = ht.Lookup(name)
			if ht != nil {
				ht.Execute(wr, data)
			} else {
				goto renderer
			}
		} else {
			goto renderer
		}
	} else {
		ht, err := this.tmpl.Clone()
		ht.Funcs(template.FuncMap(this.fmap))

		if err == nil {
			if ht != nil {
				ht.Execute(wr, data)
			} else {
				goto renderer
			}
		} else {
			goto renderer
		}
	}

	return

renderer:
	ext := ".html"
	b, err := this.renderer[ext](name, data)
	if err == nil {
		wr.Write(b)
	}
}
开发者ID:zaolab,项目名称:sunnified,代码行数:44,代码来源:publisher.go

示例8: newTtemplate

//newTtemplate adds funcmap to template var and parse files.
func newTtemplate(templateDir string) *Ttemplate {
	t := &Ttemplate{textTemplate.New("")}
	t.Funcs(textTemplate.FuncMap(funcMap))
	templateFiles := filepath.Join(templateDir, "rss1.txt")
	if util.IsFile(templateFiles) {
		_, err := t.ParseFiles(templateFiles)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		cont, err := util.Asset(path.Join("gou_template", "rss1.txt"))
		if err != nil {
			log.Fatal(err)
		}
		_, err = t.Parse(string(cont))
		if err != nil {
			log.Fatal(err)
		}
	}
	return t
}
开发者ID:shingetsu-gou,项目名称:shingetsu-gou,代码行数:22,代码来源:template.go

示例9: FromGlobs

// FromGlobs calls ParseGlob on all path globs provided and returns the
// resulting Template.
func FromGlobs(paths ...string) (*Template, error) {
	t := &Template{
		text: tmpltext.New("").Option("missingkey=zero"),
		html: tmplhtml.New("").Option("missingkey=zero"),
	}
	var err error

	t.text = t.text.Funcs(tmpltext.FuncMap(DefaultFuncs))
	t.html = t.html.Funcs(tmplhtml.FuncMap(DefaultFuncs))

	b, err := deftmpl.Asset("template/default.tmpl")
	if err != nil {
		return nil, err
	}
	if t.text, err = t.text.Parse(string(b)); err != nil {
		return nil, err
	}
	if t.html, err = t.html.Parse(string(b)); err != nil {
		return nil, err
	}

	for _, tp := range paths {
		// ParseGlob in the template packages errors if not at least one file is
		// matched. We want to allow empty matches that may be populated later on.
		p, err := filepath.Glob(tp)
		if err != nil {
			return nil, err
		}
		if len(p) > 0 {
			if t.text, err = t.text.ParseGlob(tp); err != nil {
				return nil, err
			}
			if t.html, err = t.html.ParseGlob(tp); err != nil {
				return nil, err
			}
		}
	}
	return t, nil
}
开发者ID:cherti,项目名称:alertmanager,代码行数:41,代码来源:template.go

示例10: Render

func (r *TextTemplateRenderer) Render(name string, vars librenderer.M) ([]byte, error) {
	if r.memcache == nil {
		r.memcache = make(map[string]*template.Template)
	}

	if r.memlock == nil {
		r.memlock = new(sync.Mutex)
	}

	r.memlock.Lock()
	defer r.memlock.Unlock()

	tpl, exists := r.memcache[name]
	if !exists {
		src, err := r.Assets.Asset(name)
		if err != nil {
			return []byte{}, err
		}

		tpl, err = template.New(name).Parse(string(src))
		if err != nil {
			return []byte{}, err
		}

		if r.Funcs != nil {
			tpl = tpl.Funcs(template.FuncMap(r.Funcs))
		}

		r.memcache[name] = tpl
	}

	b := new(bytes.Buffer)
	if err := tpl.Execute(b, vars); err != nil {
		return []byte{}, err
	}

	return b.Bytes(), nil
}
开发者ID:nyarla,项目名称:librenderer,代码行数:38,代码来源:text.go

示例11: Setup

// Setup runs before parsing templates
func (t *TextTemplate) Setup(helpers FuncMap) error {
	textTemplateSet = got.New("").Funcs(got.FuncMap(helpers))
	return nil
}
开发者ID:rohanthewiz,项目名称:view,代码行数:5,代码来源:template.text.go

示例12: firstMatch

}

// firstMatch executes the query q and loads the first entity into v.
func firstMatch(c appengine.Context, q *datastore.Query, v interface{}) error {
	t := q.Limit(1).Run(c)
	_, err := t.Next(v)
	if err == datastore.Done {
		err = datastore.ErrNoSuchEntity
	}
	return err
}

var (
	notifyLater = delay.Func("notify", notify)
	notifyTmpl  = template.Must(template.New("notify.txt").
			Funcs(template.FuncMap(tmplFuncs)).ParseFiles("build/notify.txt"))
)

// notify tries to update the CL for the given Commit with a failure message.
// If it doesn't succeed, it sends a failure email to golang-dev.
func notify(c appengine.Context, com *Commit, builder, logHash string) {
	var msg bytes.Buffer
	err := notifyTmpl.Execute(&msg, struct {
		Builder  string
		LogHash  string
		Hostname string
	}{builder, logHash, domain})
	if err != nil {
		c.Criticalf("couldn't render template: %v", err)
		return
	}
开发者ID:rdterner,项目名称:build,代码行数:31,代码来源:notify.go

示例13: Funcs

func (t textTemp) Funcs(funcMap FuncMap) {
	t.Template.Funcs(template.FuncMap(funcMap))
}
开发者ID:num5,项目名称:neutron,代码行数:3,代码来源:text.go

示例14: GetTextFuncMap

func GetTextFuncMap() (fc txtemplate.FuncMap) {
	return txtemplate.FuncMap(GetFuncMap())
}
开发者ID:zaolab,项目名称:sunnified,代码行数:3,代码来源:view.go

示例15: firstMatch

// firstMatch executes the query q and loads the first entity into v.
func firstMatch(c appengine.Context, q *datastore.Query, v interface{}) error {
	t := q.Limit(1).Run(c)
	_, err := t.Next(v)
	if err == datastore.Done {
		err = datastore.ErrNoSuchEntity
	}
	return err
}

var (
	sendFailMailLater = delay.Func("sendFailMail", sendFailMail)
	sendFailMailTmpl  = template.Must(
		template.New("notify.txt").
			Funcs(template.FuncMap(tmplFuncs)).
			ParseFiles("build/notify.txt"),
	)
)

func init() {
	gob.Register(&Commit{}) // for delay
}

// sendFailMail sends a mail notification that the build failed on the
// provided commit and builder.
func sendFailMail(c appengine.Context, com *Commit, builder string) {
	// TODO(adg): handle packages

	// get Result
	r := com.Result(builder, "")
开发者ID:amulyas,项目名称:bosh-cloudstack-cpi,代码行数:30,代码来源:notify.go


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