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


Golang template.Template类代码示例

本文整理汇总了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
}
开发者ID:handong890,项目名称:mobile,代码行数:25,代码来源:init_test.go

示例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
}
开发者ID:visualmotive,项目名称:gobig,代码行数:28,代码来源:gobig.go

示例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()
}
开发者ID:japettyjohn,项目名称:layoutcsv,代码行数:34,代码来源:main.go

示例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()
}
开发者ID:Serulian,项目名称:compiler,代码行数:28,代码来源:templater.go

示例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()
}
开发者ID:tw4452852,项目名称:go-src,代码行数:7,代码来源:godoc.go

示例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)
}
开发者ID:litixsoft,项目名称:lxb,代码行数:32,代码来源:create.go

示例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
}
开发者ID:alvaroloes,项目名称:sdkgen,代码行数:31,代码来源:generator.go

示例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
}
开发者ID:glerchundi,项目名称:etcd2-bootstrapper,代码行数:7,代码来源:etcd2-bootstrapper.go

示例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
}
开发者ID:nf,项目名称:icecloud,代码行数:26,代码来源:icecloud.go

示例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)
		}
	}
}
开发者ID:ceram1,项目名称:gonotify,代码行数:29,代码来源:watch.go

示例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)
	}
}
开发者ID:vin18,项目名称:tweet_words,代码行数:8,代码来源:sign_in.go

示例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)
}
开发者ID:RDurgaPrasad,项目名称:erics,代码行数:7,代码来源:main.go

示例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()

}
开发者ID:hjqhezgh,项目名称:lessgo,代码行数:31,代码来源:comp_blankpanel.go

示例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)
		}
	}
}
开发者ID:jojomi,项目名称:go-latex,代码行数:33,代码来源:latex.go

示例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))
}
开发者ID:Jacke,项目名称:alpaca,代码行数:7,代码来源:template.go


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