本文整理汇总了Golang中text/template.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: init
func init() {
var err error
fm := template.FuncMap{
"tabs": Tabs,
"goify": Goify,
"gotyperef": GoTypeRef,
"gotypedef": GoTypeDef,
"add": Add,
"publicizer": Publicizer,
"recursivePublicizer": RecursivePublicizer,
}
if simplePublicizeT, err = template.New("simplePublicize").Funcs(fm).Parse(simplePublicizeTmpl); err != nil {
panic(err)
}
if recursivePublicizeT, err = template.New("recursivePublicize").Funcs(fm).Parse(recursivePublicizeTmpl); err != nil {
panic(err)
}
if objectPublicizeT, err = template.New("objectPublicize").Funcs(fm).Parse(objectPublicizeTmpl); err != nil {
panic(err)
}
if arrayPublicizeT, err = template.New("arrPublicize").Funcs(fm).Parse(arrayPublicizeTmpl); err != nil {
panic(err)
}
if hashPublicizeT, err = template.New("hashPublicize").Funcs(fm).Parse(hashPublicizeTmpl); err != nil {
panic(err)
}
}
示例2: runTest
// Runs a test case and logs the results.
func runTest(t *testing.T, tt *deisTest, cfg *deisTestConfig) {
// Fill in the command string template from our test configuration.
var cmdBuf bytes.Buffer
tmpl := template.Must(template.New("cmd").Parse(tt.cmd))
if err := tmpl.Execute(&cmdBuf, cfg); err != nil {
t.Fatal(err)
}
cmdString := cmdBuf.String()
// Change to the target directory if needed.
if tt.dir != "" {
// Fill in the directory template from our test configuration.
var dirBuf bytes.Buffer
tmpl := template.Must(template.New("dir").Parse(tt.dir))
if err := tmpl.Execute(&dirBuf, cfg); err != nil {
t.Fatal(err)
}
dir, _ := filepath.Abs(filepath.Join(wd, dirBuf.String()))
if err := os.Chdir(dir); err != nil {
t.Fatal(err)
}
}
// TODO: Go's testing package doesn't seem to allow for reporting interim
// progress--we have to wait until everything completes (or fails) to see
// anything that was written with t.Log or t.Fatal. Interim output would
// be extremely helpful here, as this takes a while.
// Execute the command and log the input and output on error.
fmt.Printf("%v ... ", strings.TrimSpace(cmdString))
cmd := exec.Command("sh", "-c", cmdString)
if out, err := cmd.Output(); err != nil {
t.Fatalf("%v\nOutput:\n%v", err, string(out))
} else {
fmt.Println("ok")
}
}
示例3: render
func render(templName string, templ1Data interface{}, pipelineName string) (io.Reader, error) {
templateSrc, err := Asset(templName)
if err != nil {
return nil, err
}
// 1st pass
templ, err := template.New(templName + "/1").Parse(string(templateSrc))
if err != nil {
return nil, err
}
var firstRender bytes.Buffer
err = templ.Execute(&firstRender, templ1Data)
if err != nil {
return nil, err
}
// 2nd pass: some properties contain {{ .PipelineName }}
templ, err = template.New(templName + "/2").Parse(firstRender.String())
if err != nil {
return nil, fmt.Errorf("error rendering template: %s\n\ntemplate content: %s", err, firstRender.String())
}
var secondRender bytes.Buffer
err = templ.Execute(&secondRender, struct{ PipelineName string }{pipelineName})
return &secondRender, err
}
示例4: NewControllersWriter
// NewControllersWriter returns a handlers code writer.
// Handlers provide the glue between the underlying request data and the user controller.
func NewControllersWriter(filename string) (*ControllersWriter, error) {
cw := codegen.NewGoGenerator(filename)
funcMap := cw.FuncMap
funcMap["add"] = func(a, b int) int { return a + b }
funcMap["gotypename"] = codegen.GoTypeName
ctrlTmpl, err := template.New("controller").Funcs(funcMap).Parse(ctrlT)
if err != nil {
return nil, err
}
mountTmpl, err := template.New("mount").Funcs(funcMap).Parse(mountT)
if err != nil {
return nil, err
}
unmarshalTmpl, err := template.New("unmarshal").Funcs(funcMap).Parse(unmarshalT)
if err != nil {
return nil, err
}
w := ControllersWriter{
GoGenerator: cw,
CtrlTmpl: ctrlTmpl,
MountTmpl: mountTmpl,
UnmarshalTmpl: unmarshalTmpl,
}
return &w, nil
}
示例5: init
func init() {
// we see it so it doesn't use a prefix or include a time stamp.
stdout = log.New(os.Stdout, "", 0)
defaultLog = template.Must(template.New("defaultLog").Parse(defaultLogTmpl))
defaultWord = template.Must(template.New("defaultWord").Parse(defaultWordTmpl))
defaultLine = template.Must(template.New("defaultLine").Parse(defaultLineTmpl))
}
示例6: RunTemplate
func RunTemplate(reportFilename, templateFile, templateText string, out *os.File, data interface{}, format string) (err error) {
var tmpl *template.Template
var htmpl *htemplate.Template
if templateFile != "" {
if format == "html" {
htmpl, err = htemplate.New(templateFile).ParseGlob(templateFile)
} else {
tmpl, err = template.New(templateFile).ParseGlob(templateFile)
}
} else {
if format == "html" {
htmpl, err = htemplate.New(reportFilename).Parse(templateText)
} else {
tmpl, err = template.New(reportFilename).Parse(templateText)
}
}
if err != nil {
return err
}
if format == "html" {
err = htmpl.Execute(out, data)
} else {
err = tmpl.Execute(out, data)
}
if err != nil {
return err
}
return err
}
示例7: init
func init() {
globalUsageTemplate = template.Must(template.New("global_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Executable .Description}}
USAGE:
{{printf "\t%s" .Executable}} [global options] <command> [command options] [arguments...]
VERSION:
{{printf "\t%s" .Version}}
COMMANDS:{{range .Commands}}
{{printf "\t%s\t%s" .Name .Summary}}{{end}}
GLOBAL OPTIONS:{{range .Flags}}
{{printOption .Name .DefValue .Usage}}{{end}}
Run "{{.Executable}} help <command>" for more details on a specific command.
`[1:]))
commandUsageTemplate = template.Must(template.New("command_usage").Funcs(templFuncs).Parse(`
NAME:
{{printf "\t%s - %s" .Cmd.Name .Cmd.Summary}}
USAGE:
{{printf "\t%s %s %s" .Executable .Cmd.Name .Cmd.Usage}}
DESCRIPTION:
{{range $line := descToLines .Cmd.Description}}{{printf "\t%s" $line}}
{{end}}
{{if .CmdFlags}}OPTIONS:{{range .CmdFlags}}
{{printOption .Name .DefValue .Usage}}{{end}}
{{end}}For help on global options run "{{.Executable}} help"
`[1:]))
}
示例8: admin
func admin(w http.ResponseWriter, r *http.Request) {
/* import template
t, _ := template.ParseFiles("../template/shotchart.html")
t.Execute(wr io.Writer, p)
*/
temp := new(Page)
values := readDB()
buf := new(bytes.Buffer)
for _, value := range values {
if value.Content == "" {
continue
}
fmt.Println("this is reading from the database the different lines", value)
t := template.Must(template.New("form").Parse(form))
t.Execute(buf, value)
}
fmt.Println("this is the string of template", buf.String())
temp.Form = buf.String()
t := template.Must(template.New("page").Parse(adminPage))
t.Execute(w, temp)
//t := template.Must(template.New("form").Parse(form))
//t.Execute(w, Tom)
//fmt.Println("this is admin page")
}
示例9: init
func init() {
tmHeader = template.Must(template.New("header").Parse(header))
tmStruct = template.Must(template.New("modelStruct").Parse(modelStruct))
tmObjApi = template.Must(template.New("objApi").Parse(objApi))
tmQueryApi = template.Must(template.New("queryApi").Parse(queryApi))
tmManagedObjApi = template.Must(template.New("managedApi").Parse(managedApi))
}
示例10: TestTextTemplate
//-----------------------------------------------------------------------------
// Check
//-----------------------------------------------------------------------------
func TestTextTemplate(t *testing.T) {
//t.Skip("skipping TestTextTemplate")
teachers := getTeathers()
//normal
for i, td := range tmpleTests {
fmt.Printf("[%d] name:%s\n", i+1, td.tmplName)
tmpl, err := tt.New(td.tmplName).Parse(td.tmplString)
if err != nil {
t.Fatalf("[%d] template.New(%s) error: %s", i+1, td.tmplName, err)
}
err = tmpl.Execute(os.Stdout, teachers)
if err != nil {
t.Fatalf("[%d] template.Execute(%s) error: %s", i+1, td.tmplName, err)
}
}
//with func
for i, td := range tmpleTests2 {
tmpl, err := tt.New("td.tmplName").Funcs(tt.FuncMap{"plus10": plus10}).Parse(td.tmplString)
if err != nil {
t.Fatalf("[%d] template.New(%s) error: %s", i+1, td.tmplName, err)
}
err = tmpl.Execute(os.Stdout, teachers)
if err != nil {
t.Fatalf("[%d] template.Execute(%s) error: %s", i+1, td.tmplName, err)
}
}
}
示例11: PrepareJob
func (n *NatsClient) PrepareJob(jobName string) {
templateID, sha1, err := n.uploadJob(jobName)
Expect(err).NotTo(HaveOccurred())
prepareTemplateConfig := PrepareTemplateConfig{
JobName: jobName,
TemplateBlobstoreID: templateID,
RenderedTemplatesArchiveBlobstoreID: templateID,
RenderedTemplatesArchiveSHA1: sha1,
ReplyTo: senderID,
}
buffer := bytes.NewBuffer([]byte{})
t := template.Must(template.New("prepare").Parse(prepareTemplate))
err = t.Execute(buffer, prepareTemplateConfig)
Expect(err).NotTo(HaveOccurred())
prepareResponse, err := n.SendMessage(buffer.String())
Expect(err).NotTo(HaveOccurred())
_, err = n.WaitForTask(prepareResponse["value"]["agent_task_id"], -1)
Expect(err).ToNot(HaveOccurred())
buffer.Reset()
t = template.Must(template.New("apply").Parse(applyTemplate))
err = t.Execute(buffer, prepareTemplateConfig)
Expect(err).NotTo(HaveOccurred())
applyResponse, err := n.SendMessage(buffer.String())
Expect(err).NotTo(HaveOccurred())
_, err = n.WaitForTask(applyResponse["value"]["agent_task_id"], -1)
Expect(err).ToNot(HaveOccurred())
}
示例12: NewHipchatHandler
// NewHipchatHandler creates a new by reading the environment
func NewHipchatHandler() *HipchatHandler {
alertTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_TEMPLATE")
if alertTemplate == "" {
alertTemplate = `Severity {{.Severity}} alert triggered by {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
}
recoveryTemplate := os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_TEMPLATE")
if recoveryTemplate == "" {
recoveryTemplate = `Recovery of {{.CheckName}} ({{.MetricName}}: {{.Value}}). {{.URL}}`
}
hh := &HipchatHandler{
HipchatClient: &hipchat.Client{AuthToken: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_API_TOKEN")},
AlertTemplate: template.Must(template.New("alert").Parse(alertTemplate)),
RecoveryTemplate: template.Must(template.New("recovery").Parse(recoveryTemplate)),
AlertColor: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_ALERT_COLOR"),
RecoveryColor: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_RECOVERY_COLOR"),
From: os.Getenv("CIRCONUS_WEBHOOK_PROXY_HIPCHAT_FROM"),
}
if hh.AlertColor == "" {
hh.AlertColor = hipchat.ColorRed
}
if hh.RecoveryColor == "" {
hh.RecoveryColor = hipchat.ColorGreen
}
if hh.From == "" {
hh.From = "Circonus"
}
return hh
}
示例13: loadTemplates
func loadTemplates() {
templateBox := rice.MustFindBox("templates")
layout, err := templateBox.String("layout.html")
if err != nil {
log.Fatal(err)
}
t := []string{
"index",
"article",
"archive",
}
for _, tplName := range t {
tplContent, err := templateBox.String(tplName + ".html")
if err != nil {
log.Fatal(err)
}
templates[tplName] = template.Must(template.New("layout").Parse(layout + tplContent))
}
feed, err := templateBox.String("feed.atom")
if err != nil {
log.Fatal(err)
}
templates["feed.atom"] = template.Must(template.New("feed.atom").Parse(feed))
sitemap, err := templateBox.String("sitemap.xml")
if err != nil {
log.Fatal(err)
}
templates["sitemap.xml"] = template.Must(template.New("sitemap.xml").Parse(sitemap))
}
示例14: New
// New allocates a new TvRenamer with the given language, formatting, path and regexp
func New(language string, nameFormatting string, newPath string, regex string, move bool) *TvRenamer {
var err error
tvr := TvRenamer{
Language: language,
Move: move,
}
tvr.NameFormatting, err = template.New("Filename formatting").Parse(nameFormatting)
if err != nil {
log.Fatal(err)
}
tvr.NewPath, err = template.New("Path formatting").Parse(newPath)
if err != nil {
log.Fatal(err)
}
tvr.Regex, err = regexp.Compile(regex)
if err != nil {
log.Fatal(err)
}
return &tvr
}
示例15: printRegistryService
func printRegistryService(name string, port int) error {
sTemplate, err := template.New("registry").Parse(registryTemplateString)
if err != nil {
return err
}
aTemplate, err := template.New("announce").Parse(announceTemplateString)
if err != nil {
return err
}
config := new(service)
config.Name = name
config.Port = port
server, err := os.Create(fmt.Sprintf("%s/%s.service", outPath, config.Name))
if err != nil {
return err
}
announce, err := os.Create(fmt.Sprintf("%s/announce-%s.service", outPath, config.Name))
if err != nil {
return err
}
err = sTemplate.Execute(server, config)
if err != nil {
return err
}
return aTemplate.Execute(announce, config)
}