本文整理汇总了Golang中text/template.Template类的典型用法代码示例。如果您正苦于以下问题:Golang Template类的具体用法?Golang Template怎么用?Golang Template使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Template类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: diffOutput
func diffOutput(got string, wantTmpl *template.Template) (string, error) {
got = filepath.ToSlash(got)
wantBuf := new(bytes.Buffer)
data := outputData{
NDK: ndkVersion,
GOOS: goos,
GOARCH: goarch,
GOPATH: gopath,
NDKARCH: ndkarch,
BuildScript: unixBuildScript,
}
if goos == "windows" {
data.EXE = ".exe"
data.BuildScript = windowsBuildScript
}
if err := wantTmpl.Execute(wantBuf, data); err != nil {
return "", err
}
want := wantBuf.String()
if got != want {
return diff(got, want)
}
return "", nil
}
示例2: RenderPost
func (r Renderer) RenderPost(pc *PostContext, templates *template.Template) error {
err := os.MkdirAll(path.Join(r.OutputPath, pc.Slug), 0755)
if err != nil {
log.Panicf(err.Error())
}
outfile, err := os.Create(path.Join(r.OutputPath, pc.Slug, "index.html"))
if err != nil {
log.Panicf(err.Error())
}
err = templates.ExecuteTemplate(outfile, "post.html", pc)
if err != nil {
log.Panicf(err.Error())
}
// copy images
log.Printf("\"%s\": Using %d %s", pc.Slug, len(pc.Images), pluralize("image", len(pc.Images)))
for _, image := range pc.Images {
err = cp(image.SrcAbsPath, path.Join(r.OutputPath, pc.Slug, image.Filename))
if err != nil {
log.Panicf(err.Error())
}
}
log.Printf("\"%s\": Done rendering", pc.Slug)
return nil
}
示例3: processFile
func processFile(fc FileConfig, t *template.Template) {
// in file
iFile, err := os.Open(fc.Name)
if err != nil {
panic("Can't open " + fc.Name)
}
defer iFile.Close()
// out file
oFile, err := os.Create(fc.Name + "_out.txt")
if err != nil {
panic("Can't open/write to " + fc.Name + "_out.txt")
}
defer oFile.Close()
r := csv.NewReader(iFile)
r.Comma = '\t'
r.TrailingComma = true
record, err := r.Read()
for i := 0; err == nil; record, err = r.Read() {
if i == 0 {
t.ExecuteTemplate(oFile, fc.TemplateName+"_H", makeTemplateContext(&record))
}
i = i + 1
if i <= fc.Skip {
continue
}
oFile.Write([]byte("\n"))
t.ExecuteTemplate(oFile, fc.TemplateName, makeTemplateContext(&record))
}
fmt.Println(err)
oFile.Sync()
}
示例4: Execute
// execute runs the given go-template over the given context.
func (temp *Templater) Execute(name string, templateStr string, context interface{}) string {
var parsed *template.Template = nil
// Check the cache.
cached, isCached := temp.templateCache.Get(templateStr)
if !isCached {
t := template.New(name)
parsedTemplate, err := t.Parse(templateStr)
if err != nil {
panic(err)
}
temp.templateCache.Set(templateStr, parsedTemplate)
parsed = parsedTemplate
} else {
parsed = cached.(*template.Template)
}
// Execute the template.
var source bytes.Buffer
eerr := parsed.Execute(&source, context)
if eerr != nil {
panic(eerr)
}
return source.String()
}
示例5: applyTemplate
func applyTemplate(t *template.Template, name string, data interface{}) []byte {
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
log.Printf("%s.Execute: %s", name, err)
}
return buf.Bytes()
}
示例6: templateWorker
// templateWorker create file from template
// done channel send nil or error back
func templateWorker(tpl *template.Template, ftpl FileTemplates, done chan error) {
// check file template path
ok, err := utils.PathExists(ftpl.Path)
if err != nil {
done <- err
return
}
// file template path not exists, create new file template path
if !ok {
if err := os.MkdirAll(ftpl.Path, 0755); err != nil {
done <- err
return
}
}
// create new target file
f, err := os.OpenFile(filepath.Join(ftpl.Path, ftpl.Target), os.O_WRONLY|os.O_CREATE, 0755)
if err != nil {
done <- err
return
}
defer f.Close()
// generate file content,
// send return to channel (nil or err)
done <- tpl.ExecuteTemplate(f, ftpl.Tpl, ftpl.Vars)
}
示例7: generatePerModelFiles
func (g *Generator) generatePerModelFiles(templateFileNames []string, modelTpls *template.Template, modelsDir string, filter func(modelInfo *modelInfo) bool) error {
for _, tplFileName := range templateFileNames {
tplName := filepath.Base(tplFileName)
// Apply the templates to each model in the API
for _, modelInfo := range g.modelsInfo {
if filter(modelInfo) {
continue
}
// TODO: Do this concurrently
repl := strings.NewReplacer(
templateExt, "",
fileNameModelNameInterpolation, modelInfo.Name,
fileNameAPINameInterpolation, g.config.APIName,
fileNameAPIPrefixInterpolation, g.config.APIPrefix,
)
fileName := repl.Replace(tplName)
err := generateFile(path.Join(modelsDir, fileName), modelTpls.Lookup(tplName), templateData{
Config: g.config,
API: g.api,
CurrentModelInfo: modelInfo,
AllModelsInfo: g.modelsInfo,
AuthInfo: g.authInfo,
CurrentTime: time.Now(),
})
if err != nil {
return errors.Annotatef(err, "when generating model or service %q", modelInfo.Name)
}
}
}
return nil
}
示例8: executeTemplate
func executeTemplate(tmpl *template.Template, data interface{}) (string, error) {
var cmdBuffer bytes.Buffer
if err := tmpl.Execute(&cmdBuffer, data); err != nil {
return "", err
}
return cmdBuffer.String(), nil
}
示例9: writePlaylist
func (c *Config) writePlaylist(mount, ext string, t *template.Template) error {
for i, s := range c.Server {
if s.Kind == "master" {
continue
}
url := fmt.Sprintf("%s%s", c.ServerURL(s), mount)
servers := []string{url}
for j, s := range c.Server {
if s.Kind == "master" || i == j {
continue
}
url := fmt.Sprintf("%s%s", c.ServerURL(s), mount)
servers = append(servers, url)
}
name := fmt.Sprintf("%s-%s.%s", mount, s.Name, ext)
f, err := os.Create(name)
if err != nil {
return err
}
if err := t.Execute(f, servers); err != nil {
return err
}
f.Close()
}
return nil
}
示例10: waitForWatcher
func waitForWatcher(ctx context.Context, watcher *inotify.Watcher, match matcherFunc, tpl *template.Template, monitor bool) {
defer watcher.Close()
for {
select {
case <-ctx.Done(): // Timeout
os.Exit(2)
return
case ev := <-watcher.Event:
if !match(ev) {
break
}
if tpl != nil {
tpl.Execute(os.Stdout, ev)
log.Infoln()
} else {
log.Infoln(ev)
}
// Finish if not monitoring mode.
if !monitor {
return
}
case err := <-watcher.Error:
log.Fatal(err)
}
}
}
示例11: Respond
// respond responds to a request by executing the html template t with data.
func Respond(w http.ResponseWriter, t *template.Template, data interface{}) {
fmt.Println("Respond")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := t.Execute(w, data); err != nil {
log.Print(err)
}
}
示例12: writeTmpl
func writeTmpl(tmpl *template.Template, vmConfigs []vm) {
file, err := os.Create(tmpl.Name())
checkError(err)
defer file.Close()
err = tmpl.Execute(file, vmConfigs)
checkError(err)
}
示例13: generate
func (blankPanel blankPanel) generate(terminal, packageName string, employee Employee) []byte {
var t *template.Template
var buf bytes.Buffer
t = template.New("blankpanel.html")
t, err := t.ParseFiles("../lessgo/template/component/" + terminal + "/blankpanel.html")
if err != nil {
Log.Error(err.Error())
return []byte{}
}
data := make(map[string]interface{})
data["BlankPanel"] = blankPanel
data["Terminal"] = terminal
data["Employee"] = employee
err = t.Execute(&buf, data)
if err != nil {
Log.Error(err.Error())
return []byte{}
}
return buf.Bytes()
}
示例14: ExecuteTemplate
// ExecuteTemplate executes a template on the source TeX files.
func (t *CompileTask) ExecuteTemplate(templ *template.Template, data interface{}, inputFilename string, outputFilename string) {
sc := t.context()
useTempFile := outputFilename == ""
if useTempFile {
outputFilename = sc.MustGetTempFile().Name()
}
inputFilename = sc.AbsPath(t.defaultCompileFilename(inputFilename))
f, err := os.Create(sc.AbsPath(outputFilename))
if err != nil {
panic(err)
}
w := io.Writer(f)
err = templ.ExecuteTemplate(w, filepath.Base(inputFilename), data)
if err != nil {
panic(err)
}
f.Close()
if useTempFile {
// copy back, remove temp
err = os.Remove(inputFilename)
if err != nil {
panic(err)
}
err = sc.CopyFile(outputFilename, inputFilename)
if err != nil {
panic(err)
}
}
}
示例15: WriteTemplate
func WriteTemplate(temp *template.Template, out string, data interface{}) {
file, err := os.Create(path.Clean(out))
defer file.Close()
HandleError(err)
HandleError(temp.Execute(file, data))
}