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


Golang Template.Execute方法代码示例

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


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

示例1: Transform

func (ctx *TemplateContext) Transform(writer io.Writer, descriptor string) error {
	var t *template.Template

	if b, err := ioutil.ReadFile(descriptor); err != nil {
		return err
	} else {
		var e error
		t = template.New(descriptor).Funcs(Funcs)
		t, e = t.Parse(string(b))
		if e != nil {
			return e
		}
		if matches, err := filepath.Glob("./**/*.tmpl"); err == nil && len(matches) > 0 {
			if t, e = t.ParseFiles(matches...); err != nil {
				return err
			}
		}
	}
	environment := viper.GetString(ENV_NAME)
	m := ctx.mergeAppWithDefault(strings.ToLower(environment))

	if err := t.Execute(writer, m); err != nil {
		return err
	}
	return nil
}
开发者ID:ContainX,项目名称:depcon,代码行数:26,代码来源:templatectx.go

示例2: Render

// Render updates the given destinationPath according to the given template and options.
// Returns true if the file was created or changed, false if nothing has changed.
func Render(templateName, destinationPath string, options interface{}, destinationFileMode os.FileMode) (bool, error) {
	asset, err := Asset(templateName)
	if err != nil {
		return false, maskAny(err)
	}

	// parse template
	var tmpl *template.Template
	tmpl = template.New(templateName)
	funcMap := template.FuncMap{
		"escape": escape,
		"quote":  strconv.Quote,
	}
	tmpl.Funcs(funcMap)
	_, err = tmpl.Parse(string(asset))
	if err != nil {
		return false, maskAny(err)
	}
	// execute template to buffer
	buf := &bytes.Buffer{}
	tmpl.Funcs(funcMap)
	err = tmpl.Execute(buf, options)
	if err != nil {
		return false, maskAny(err)
	}

	// Update file
	changed, err := util.UpdateFile(destinationPath, buf.Bytes(), destinationFileMode)
	return changed, maskAny(err)
}
开发者ID:pulcy,项目名称:gluon,代码行数:32,代码来源:render.go

示例3: 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

示例4: Render

/*
 * Render page
 *
 * @param pageFilePath (string)
 * @param w            (http.ResponseWriter)
 *
 * @return (error)
 */
func (page *Page) Render(pageFilePath string, w http.ResponseWriter) (err error) {
	columnFilePath := page.PageSetting.Layout + ".html"
	mainFilePath := "main.html"
	contentFilePath := pageFilePath + ".html"
	sidebarFilePath := "sidebar.html"

	var tmpl *template.Template

	switch page.PageSetting.ShowSidebar {
	case true:
		tmpl, err = template.ParseFiles(
			LAYOUT_FOLDER+mainFilePath,
			LAYOUT_FOLDER+columnFilePath,
			LAYOUT_FOLDER+sidebarFilePath,
			STATIC_FOLDER+contentFilePath)
	case false:
		tmpl, err = template.ParseFiles(
			LAYOUT_FOLDER+mainFilePath,
			LAYOUT_FOLDER+columnFilePath,
			STATIC_FOLDER+contentFilePath)

	}

	if err != nil {
		return
	}

	tmpl.Execute(w, page)
	return
}
开发者ID:woodycarl,项目名称:Gorbled,代码行数:38,代码来源:page.go

示例5: execTmpl

// execTmpl executes the provided template on the data, emitting the string.
// It presumes that the input data is semantically correct for the template.
func execTmpl(t *template.Template, data interface{}) string {
	var b bytes.Buffer
	if err := t.Execute(&b, data); err != nil {
		panic("drum: " + err.Error())
	}
	return b.String()
}
开发者ID:billyboar,项目名称:GCSolutions,代码行数:9,代码来源:pattern.go

示例6: getServiceURLWithClient

func getServiceURLWithClient(client *unversioned.Client, ip, namespace, service string, t *template.Template) (string, error) {
	port, err := getServicePort(client, namespace, service)
	if err != nil {
		return "", err
	}

	var doc bytes.Buffer
	err = t.Execute(&doc, ipPort{ip, port})
	if err != nil {
		return "", err
	}

	u, err := url.Parse(doc.String())
	if err != nil {
		return "", err
	}

	annotations, err := getServiceAnnotations(client, namespace, service)
	if err != nil {
		return "", err
	}

	if scheme, ok := annotations[serviceAPIAnnotationScheme]; ok {
		u.Scheme = scheme
	}
	if path, ok := annotations[serviceAPIAnnotationPath]; ok && len(u.Path) == 0 {
		u.Path = path
	}

	return u.String(), nil
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:31,代码来源:cluster.go

示例7: generateCode

func generateCode(outputFile string, tmpl *template.Template, pkg string, parsed *parser.Thrift) error {
	wrappedServices, err := wrapServices(parsed)
	if err != nil {
		log.Fatalf("Service parsing error: %v", err)
	}

	buf := &bytes.Buffer{}

	td := TemplateData{
		Package:        pkg,
		Services:       wrappedServices,
		ThriftImport:   *apacheThriftImport,
		TChannelImport: tchannelThriftImport,
	}
	if err := tmpl.Execute(buf, td); err != nil {
		return fmt.Errorf("failed to execute template: %v", err)
	}

	generated := cleanGeneratedCode(buf.Bytes())
	if err := ioutil.WriteFile(outputFile, generated, 0666); err != nil {
		return fmt.Errorf("cannot write output file %s: %v", outputFile, err)
	}

	// Run gofmt on the file (ignore any errors)
	exec.Command("gofmt", "-w", outputFile).Run()
	return nil
}
开发者ID:hustxiaoc,项目名称:tchannel,代码行数:27,代码来源:main.go

示例8: 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

示例9: 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

示例10: play

/**
 * 単語学習ページの表示
 * play.html 学習ページ全体のテンプレート
 */
func play(w http.ResponseWriter, r *http.Request) {
	type Contents struct {
		Words string
	}

	var c appengine.Context
	var u *user.User
	var contents *Contents
	var err error
	var page *template.Template
	var entities []Entity
	var bytes []byte

	c = appengine.NewContext(r)
	u = user.Current(c)

	// 単語一覧を取得
	entities = get(c, u)

	// JSONに変換
	bytes, err = json.Marshal(entities)
	Check(c, err)
	contents = new(Contents)
	contents.Words = string(bytes)

	// ページテンプレート取得
	page, err = template.ParseFiles("server/play.html")
	Check(c, err)

	// 表示
	page.Execute(w, contents)
}
开发者ID:yokano,项目名称:tango,代码行数:36,代码来源:play.go

示例11: ShowMessage

// ShowMessage opens a message dialog to show the user a message.
func (w *Workflow) ShowMessage(message string) (err error) {
	script :=
		`tell application "Alfred {{.Version}}"
			  activate
			  set alfredPath to (path to application "Alfred {{.Version}}")
			  set alfredIcon to path to resource "appicon.icns" in bundle (alfredPath as alias)
			  display dialog "{{.Prompt}}" with title "{{.Title}}" buttons {"Ok"} default button "Ok" with icon alfredIcon
		  end tell`

	data := struct {
		Version string
		Prompt  string
		Title   string
	}{os.Getenv("alfred_short_version"), message, w.name}

	var tmpl *template.Template
	tmpl, err = template.New("script").Parse(script)
	if err != nil {
		return
	}

	var buf bytes.Buffer
	err = tmpl.Execute(&buf, data)
	if err != nil {
		return
	}

	script = buf.String()
	_, err = RunScript(script)
	return
}
开发者ID:jason0x43,项目名称:go-alfred,代码行数:32,代码来源:workflow.go

示例12: logrotateRender

func (slConfig *SyslogConfig) logrotateRender(t *template.Template) ([]byte, error) {
	var buffer bytes.Buffer
	if err := t.Execute(&buffer, slConfig); err != nil {
		return nil, err
	}
	return buffer.Bytes(), nil
}
开发者ID:claudiu-coblis,项目名称:juju,代码行数:7,代码来源:config.go

示例13: writePri

func (pw PackageWrapper) writePri(filename string, tpl *template.Template, data interface{}) error {

	var file *os.File
	var err error

	// create the vendor directory if needed
	if _, err = os.Stat(core.Vendor); err != nil {
		err = os.Mkdir(core.Vendor, 0755)
	}

	// re-create the .pri file
	file, err = os.Create(filename)

	if err != nil {
		return err
	}
	defer file.Close()

	err = tpl.Execute(file, data)
	if err != nil {
		return err
	}

	return nil
}
开发者ID:gitter-badger,项目名称:qpm,代码行数:25,代码来源:package.go

示例14: createDockerfile

// Generate a dockerfile for the given deployment
func createDockerfile(d *DeployInfo) ([]byte, error) {
	// use de-reference to create a copy
	info := *d

	var buf bytes.Buffer
	var tmpl *template.Template
	switch d.Lang {
	case Python2:
		tmpl = pyTmpl

		if info.BaseImage == "" {
			info.BaseImage = "yhat/scienceops-python:0.0.2"
		}

	case R:
		if d.CRANMirror == "" {
			// Create a copy of the DeployInfo to appease the race detector.
			info.CRANMirror = YhatCRANMirror
		}
		if info.BaseImage == "" {
			info.BaseImage = "yhat/scienceops-r:0.0.2"
		}

		tmpl = rTmpl
	default:
		return nil, fmt.Errorf("unrecognized language passed to dockerfile generation '%s'", d.Lang)
	}
	if err := tmpl.Execute(&buf, &info); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
开发者ID:yhat,项目名称:workload-simulator,代码行数:33,代码来源:deploy.go

示例15: genConfig

func genConfig(appPath string, data map[string]string) error {
	var src, dest *os.File
	var fileContent []byte
	var err error
	var tmpl *template.Template
	name := filepath.Join(appPath, "conf", "app.cnf.template")

	if src, err = os.Open(name); err != nil {
		return err
	}
	tmpfile := name
	defer func() { src.Close(); os.Remove(tmpfile) }()
	name = filepath.Join(appPath, "conf", "app.cnf")
	if dest, err = os.OpenFile(name, os.O_CREATE|os.O_WRONLY, 0666); err != nil {
		return nil
	}
	defer dest.Close()
	if fileContent, err = ioutil.ReadAll(src); err != nil {
		return err
	}
	if tmpl, err = template.New("").Parse(string(fileContent)); err != nil {
		return err
	}
	return tmpl.Execute(dest, data)
}
开发者ID:Joinhack,项目名称:peony,代码行数:25,代码来源:new.go


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