本文整理汇总了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
}
示例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)
}
示例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)
}
示例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...))
}
示例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)
}
示例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")
}
示例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)
}
}
示例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
}
示例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
}
示例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
}
示例11: Setup
// Setup runs before parsing templates
func (t *TextTemplate) Setup(helpers FuncMap) error {
textTemplateSet = got.New("").Funcs(got.FuncMap(helpers))
return nil
}
示例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
}
示例13: Funcs
func (t textTemp) Funcs(funcMap FuncMap) {
t.Template.Funcs(template.FuncMap(funcMap))
}
示例14: GetTextFuncMap
func GetTextFuncMap() (fc txtemplate.FuncMap) {
return txtemplate.FuncMap(GetFuncMap())
}
示例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, "")