本文整理汇总了Golang中text/template.Template.Lookup方法的典型用法代码示例。如果您正苦于以下问题:Golang Template.Lookup方法的具体用法?Golang Template.Lookup怎么用?Golang Template.Lookup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类text/template.Template
的用法示例。
在下文中一共展示了Template.Lookup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Register
func Register(templates *template.Template) {
// http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
// // Load template according to the requested path, excluding the leading "/"
// requestedFile := req.URL.Path[1:]
// template := templates.Lookup(requestedFile + ".html")
//
// var context interface{} = nil
// context = viewmodels.Get("My Title", requestedFile)
//
// if template != nil {
// template.Execute(w, context)
// } else {
// w.WriteHeader(404)
// w.Write([]byte("404 - " + http.StatusText(404)))
// }
// })
ic := new(indexController)
ic.template = templates.Lookup("index.html")
http.HandleFunc("/index", ic.get)
cc := new(categoriesController)
cc.template = templates.Lookup("categories.html")
http.HandleFunc("/categories", cc.get)
// redirect /img/ and /css/ dir to assets/img/ and assets/css/
http.HandleFunc("/img/", serveAssets)
http.HandleFunc("/css/", serveAssets)
}
示例2: 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
}
示例3: addDependencies
func (t *Repository) addDependencies(templ *template.Template) (*template.Template, error) {
name := templ.Name()
deps := t.flattenDependencies(templ, nil)
for dep := range deps {
if dep == "" {
continue
}
tt := templ.Lookup(dep)
// Check if we have it
if tt == nil {
tt = t.templates[dep]
// Still dont have it return an error
if tt == nil {
return templ, fmt.Errorf("Could not find template %s", dep)
}
var err error
// Add it to the parse tree
templ, err = templ.AddParseTree(dep, tt.Tree)
if err != nil {
return templ, fmt.Errorf("Dependency Error: %v", err)
}
}
}
return templ.Lookup(name), nil
}
示例4: getTemplate
func (m ModelMeta) getTemplate(tmpl *template.Template, name string, defaultTmpl *template.Template) *template.Template {
if tmpl != nil {
if definedTmpl := tmpl.Lookup(name); definedTmpl != nil {
return definedTmpl
}
}
return defaultTmpl
}
示例5: executeTemplate
func executeTemplate(rootTemplte *template.Template, templateName string, machine datasource.Machine, hostAddr string) (string, error) {
template := rootTemplte.Lookup(templateName)
if template == nil {
return "", fmt.Errorf("template with name=%s wasn't found for root=%s",
templateName, rootTemplte)
}
buf := new(bytes.Buffer)
template.Funcs(map[string]interface{}{
"V": func(key string) string {
flag, err := machine.GetFlag(key)
if err != nil { // TODO excepts Not-Found
logging.Log(templatesDebugTag,
"Error while getting flag key=%s for machine=%s: %s",
key, machine.Name(), err)
return ""
}
return flag
},
"b64": func(text string) string {
return base64.StdEncoding.EncodeToString([]byte(text))
},
"b64template": func(templateName string) string {
text, err := executeTemplate(rootTemplte, templateName, machine, hostAddr)
if err != nil {
logging.Log(templatesDebugTag,
"Error while b64template for templateName=%s machine=%s: %s",
templateName, machine.Name(), err)
return ""
}
return base64.StdEncoding.EncodeToString([]byte(text))
},
})
ip, _ := machine.IP()
data := struct {
Mac string
IP string
Hostname string
Domain string
HostAddr string
}{
machine.Mac().String(),
ip.String(),
machine.Name(),
machine.Domain(),
hostAddr,
}
err := template.ExecuteTemplate(buf, templateName, &data)
if err != nil {
return "", err
}
str := buf.String()
str = strings.Trim(str, "\n")
return str, nil
}
示例6: FormatNotification
func FormatNotification(t *template.Template, n lonelycat.Notification) (string, error) {
tpl := t.Lookup(n.Type)
if tpl == nil {
return "", ErrNoTemplate
}
var buf bytes.Buffer
err := tpl.Execute(&buf, n)
if err != nil {
return "", err
}
return strings.TrimSpace(buf.String()), nil
}
示例7: SetTemplate
func SetTemplate(t *template.Template, name, filename string) error {
// Read template
buf, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
// Update if exists
if tt := t.Lookup(name); tt != nil {
_, err = tt.Parse(string(buf))
return err
}
// Allocate new name if not
_, err = t.New(name).Parse(string(buf))
return err
}
示例8: Register
func Register(template *template.Template) {
uc := new(usersController)
uc.template = template.Lookup("users.html")
http.HandleFunc("/users", uc.serveUsers)
http.HandleFunc("/ws", serveWs)
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
}
示例9: Register
func Register(templates *template.Template) {
// http.HandleFunc("/",
// func(w http.ResponseWriter, r *http.Request) {
// requestedFile := r.URL.Path[1:]
// template := templates.Lookup(requestedFile + ".html")
// fmt.Printf(requestedFile + "\n")
//
// var context interface{}
// switch requestedFile {
// case "home":
// context = viewmodels.GetHome()
// case "404":
// context = viewmodels.Get404()
// default:
// template = templates.Lookup("404" + ".html")
// context = viewmodels.Get404()
// w.WriteHeader(404)
// fmt.Printf("Showing 404 page \n")
// }
// if template != nil {
// template.Execute(w, context)
// } else {
//
// }
// })
//Home route
hc := new(homeController)
hc.template = templates.Lookup("home.html")
http.HandleFunc("/home", hc.get)
//Lights route
lc := new(lightsController)
lc.template = templates.Lookup("lights.html")
http.HandleFunc("/lights", lc.get)
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
}
示例10: mergeTemplate
// Returns a copy of the root template with the supplied template merged in.
func (ts *Templates) mergeTemplate(t *template.Template) (out *template.Template, err error) {
defer func() {
if r := recover(); r != nil {
// Seems to be a bug with cloning empty templates.
err = fmt.Errorf("Problem cloning template: %v", r)
}
}()
if ts.empty {
out = template.New("root")
} else {
if out, err = ts.root.Clone(); err != nil {
return
}
}
for _, tmpl := range t.Templates() {
ptr := out.Lookup(tmpl.Name())
if ptr == nil {
out.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, tmpl.Name()))
ptr = out.Lookup(tmpl.Name())
}
var clone *template.Template
if clone, err = tmpl.Clone(); err != nil {
return
}
(*ptr) = *clone
// Merge existing root templates back into new template.
for _, out_tmpl := range out.Templates() {
ptr2 := clone.Lookup(out_tmpl.Name())
if ptr2 == nil {
clone.Parse(fmt.Sprintf(`{{define "%v"}}{{end}}`, out_tmpl.Name()))
ptr2 = clone.Lookup(out_tmpl.Name())
(*ptr2) = *out_tmpl
}
}
}
return
}
示例11: generateGeneralFiles
func (g *Generator) generateGeneralFiles(templateFileNames []string, generalTpls *template.Template, apiDir string) error {
for _, tplFileName := range templateFileNames {
tplName := filepath.Base(tplFileName)
// TODO: Do this concurrently
// Get the name of the file, replacing some special strings in the template name
repl := strings.NewReplacer(
templateExt, "",
fileNameAPINameInterpolation, g.config.APIName,
fileNameAPIPrefixInterpolation, g.config.APIPrefix,
)
fileName := repl.Replace(tplName)
err := generateFile(path.Join(apiDir, fileName), generalTpls.Lookup(tplName), templateData{
Config: g.config,
API: g.api,
AllModelsInfo: g.modelsInfo,
CurrentTime: time.Now(),
AuthInfo: g.authInfo,
})
if err != nil {
return errors.Annotatef(err, "when generating API file %q", fileName)
}
}
return nil
}
示例12: Register
func Register(templates *template.Template) {
router := mux.NewRouter()
hc := new(homeController)
hc.template = templates.Lookup("home.html")
router.HandleFunc("/home", hc.get)
cc := new(categoriesController)
cc.template = templates.Lookup("categories.html")
router.HandleFunc("/categories", cc.get)
categoryController := new(categoryController)
categoryController.template = templates.Lookup("products.html")
router.HandleFunc("/categories/{id}", categoryController.get)
http.Handle("/", router)
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
}
示例13: executeTemplate
func executeTemplate(rootTemplte *template.Template, templateName string,
ds datasource.DataSource, machineInterface datasource.MachineInterface,
webServerAddr string) (string, error) {
template := rootTemplte.Lookup(templateName)
if template == nil {
return "", fmt.Errorf("template with name=%s wasn't found for root=%v",
templateName, rootTemplte)
}
mac := machineInterface.Mac().String()
buf := new(bytes.Buffer)
template.Funcs(map[string]interface{}{
"V": func(key string) string {
value, err := machineInterface.GetVariable(key)
if err != nil {
log.WithField("where", "templating.executeTemplate").WithError(err).Warn(
"error while GetVariable")
}
return value
},
"b64": func(text string) string {
return base64.StdEncoding.EncodeToString([]byte(text))
},
"b64template": func(templateName string) string {
text, err := executeTemplate(rootTemplte, templateName, ds, machineInterface, webServerAddr)
if err != nil {
log.WithField("where", "templating.executeTemplate").WithError(err).Warnf(
"error while executeTemplate(templateName=%s machine=%s)",
templateName, mac)
return ""
}
return base64.StdEncoding.EncodeToString([]byte(text))
},
})
etcdMembers, _ := ds.EtcdMembers()
machine, err := machineInterface.Machine(false, nil)
if err != nil {
return "", err
}
data := struct {
Mac string
IP string
Hostname string
Domain string
WebServerAddr string
EtcdEndpoints string
}{
mac,
machine.IP.String(),
machineInterface.Hostname(),
ds.ClusterName(),
webServerAddr,
etcdMembers,
}
err = template.ExecuteTemplate(buf, templateName, &data)
if err != nil {
return "", err
}
str := buf.String()
str = strings.Trim(str, "\n")
return str, nil
}
示例14: toQualtrics
func (form *Form) toQualtrics(out io.Writer, templates *template.Template) (err error) {
out.Write([]byte("[[AdvancedFormat]]"))
var (
field, next_field *Field
qualtrics_field *qualtricsField
qualtrics_type string
i int = 0
num_fields = len(form.Fields)
)
for i < num_fields {
field = &form.Fields[i]
//attempt to link a question with its answer, based on the assumption that most
//answer fields follow a 'question' field. If a question is followed by a question,
//render the first one as a simple instruction field
if field.SType == "question" {
if i < num_fields-1 {
next_field = &form.Fields[i+1]
if next_field.SType == "question" {
qualtrics_type, err = getQualtricsType(field)
if err != nil {
return
}
qualtrics_field = &qualtricsField{
Question: field,
QuestionTemplate: templates.Lookup("instruction"),
QualtricsType: qualtrics_type,
Answer: nil,
AnswerTemplate: nil,
}
} else {
//if this field has no html text, but answer has s-label, skip this field
//and, on next iteration, convert the field label into a question
if len(field.Html) == 0 && len(next_field.SLabel) > 0 {
i++
continue
}
qualtrics_type, err = getQualtricsType(next_field)
if err != nil {
return
}
qualtrics_field = &qualtricsField{
Question: field,
QuestionTemplate: templates.Lookup("question"),
QualtricsType: qualtrics_type,
Answer: next_field,
AnswerTemplate: templates.Lookup(form.getTemplateName(next_field)),
}
i++
}
} else {
qualtrics_field = &qualtricsField{
Question: field,
QuestionTemplate: templates.Lookup("instruction"),
Answer: nil,
AnswerTemplate: nil,
}
}
} else {
qualtrics_type, err = getQualtricsType(field)
if err != nil {
return
}
var question *Field = nil
var question_tpl *template.Template = nil
if len(field.SLabel) > 0 {
question = &Field{
SId: field.SId,
SType: "question",
Html: field.SLabel,
}
question_tpl = templates.Lookup("question")
}
qualtrics_field = &qualtricsField{
Question: question,
QuestionTemplate: question_tpl,
Answer: field,
QualtricsType: qualtrics_type,
AnswerTemplate: templates.Lookup(form.getTemplateName(field)),
}
}
//output question
if qualtrics_field.Question != nil {
if qualtrics_field.QuestionTemplate == nil {
err = fmt.Errorf("Question template not found for field %d: %s", i+1, qualtrics_field.Question)
return
}
err = qualtrics_field.QuestionTemplate.Execute(out, qualtrics_field)
if err != nil {
return
}
}
//output answer
//.........这里部分代码省略.........
示例15: Register
func Register(templates *template.Template) {
router := mux.NewRouter()
hc := new(homeController)
hc.template = templates.Lookup("home.html")
router.HandleFunc("/home", hc.get)
cc := new(categoriesController)
cc.template = templates.Lookup("categories.html")
router.HandleFunc("/categories", cc.get)
categoryController := new(categoryController)
categoryController.template = templates.Lookup("products.html")
router.HandleFunc("/categories/{id}", categoryController.get)
productController := new(productController)
productController.template = templates.Lookup("product.html")
router.HandleFunc("/products/{id}", productController.get)
profileController := new(profileController)
profileController.template = templates.Lookup("profile.html")
router.HandleFunc("/profile", profileController.handle)
standLocatorCtrl := new(standLocatorController)
standLocatorCtrl.template = templates.Lookup("stand_locator.html")
router.HandleFunc("/stand_locator", standLocatorCtrl.get)
router.HandleFunc("/api/stand_locator", standLocatorCtrl.apiSearch)
http.Handle("/", router)
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
}