本文整理汇总了Golang中html/template.Template.ParseFiles方法的典型用法代码示例。如果您正苦于以下问题:Golang Template.ParseFiles方法的具体用法?Golang Template.ParseFiles怎么用?Golang Template.ParseFiles使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类html/template.Template
的用法示例。
在下文中一共展示了Template.ParseFiles方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: getTemplateInstance
func (v *View) getTemplateInstance(tpl []string) (*template.Template, error) {
key := strings.Join(tpl, "-")
// if IsCache, get cached template if exist
if v.IsCache {
if v.templateCache[key] != nil {
return v.templateCache[key], nil
}
}
var (
t *template.Template
e error
file []string = make([]string, len(tpl))
)
for i, tp := range tpl {
file[i] = path.Join(v.Dir, tp)
}
t = template.New(path.Base(tpl[0]))
t.Funcs(v.FuncMap)
t, e = t.ParseFiles(file...)
if e != nil {
return nil, e
}
if v.IsCache {
v.templateCache[key] = t
}
return t, nil
}
示例2: ParseGlob
// Pase files match the [pattern] and store file path of each template name in templateMapPaths
func ParseGlob(templates *template.Template, pattern string) (*template.Template, error) {
filePaths, err := filepath.Glob(pattern)
if err != nil {
return templates, err
}
if len(filePaths) == 0 {
return templates, fmt.Errorf("mangotemplate.ParseGlob: pattern matches no files: %#q", pattern)
}
for _, path := range filePaths {
_, err := templates.ParseFiles(path)
if err != nil {
return templates, err
}
for _, parsedTemplate := range templates.Templates() {
if _, ok := templateMapPaths[parsedTemplate.Name()]; ok {
continue
}
templateMapPaths[parsedTemplate.Name()] = path
}
}
return templates, nil
}
示例3: main
func main() {
var err error
var tpl *template.Template
tpl, err = tpl.ParseFiles("tpl.gohtml", "tpl2.gohtml")
if err != nil {
log.Fatalln(err)
}
err = tpl.Execute(os.Stdout, Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
fmt.Println("\n***************")
err = tpl.ExecuteTemplate(os.Stdout, "tpl.gohtml", Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
fmt.Println("\n***************")
err = tpl.ExecuteTemplate(os.Stdout, "tpl2.gohtml", Page{
Title: "My Title 2",
Body: "hello world",
})
if err != nil {
log.Fatalln(err)
}
}
示例4: FindTemplate
func (context *Context) FindTemplate(tmpl *template.Template, layout string) (*template.Template, error) {
for _, p := range context.getViewPaths() {
if _, err := os.Stat(path.Join(p, layout)); !os.IsNotExist(err) {
if tmpl, err = tmpl.ParseFiles(path.Join(p, layout)); err != nil {
fmt.Println(err)
} else {
return tmpl, nil
}
}
}
return tmpl, errors.New("template not found")
}
示例5: Register
// Register loads all view template files found in 'folder'
func Register(folder string, t *template.Template) {
templates := []string{}
filepath.Walk(folder, func(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
templates = append(templates, path)
}
return nil
})
t.ParseFiles(templates...)
}
示例6: parseAllPartials
func parseAllPartials(appDir string, t *template.Template) (*template.Template, error) {
var partials []string
walkPartials := func(path string, f os.FileInfo, err error) error {
switch filepath.Ext(path) {
case ".html":
fmt.Println(path)
partials = append(partials, path)
}
return nil
}
root := fmt.Sprintf("%s/views/partials", appDir)
//for appDir/views/partials, load all files in that directory into partials
filepath.Walk(root, walkPartials)
return t.ParseFiles(partials...)
}
示例7: Execute
func (context *Context) Execute(name string, result interface{}) {
var tmpl *template.Template
var cacheKey string
if name == "show" && !context.Resource.isSetShowAttrs {
name = "edit"
}
if context.Action == "" {
context.Action = name
}
if context.Resource != nil {
cacheKey = path.Join(context.resourcePath(), name)
} else {
cacheKey = name
}
if t, ok := templates[cacheKey]; !ok || true {
if file, err := context.FindTemplate("layout.tmpl"); err == nil {
if tmpl, err = template.New(filepath.Base(file)).Funcs(context.FuncMap()).ParseFiles(file); err == nil {
for _, name := range []string{"header", "footer"} {
if tmpl.Lookup(name) == nil {
if file, err := context.FindTemplate(name + ".tmpl"); err == nil {
tmpl.ParseFiles(file)
}
} else {
utils.ExitWithMsg(err)
}
}
} else {
utils.ExitWithMsg(err)
}
}
} else {
tmpl = t
}
context.Result = result
context.Content = context.Render(name, result)
if err := tmpl.Execute(context.Writer, context); err != nil {
utils.ExitWithMsg(err)
}
}
示例8: getInstance
func (this *View) getInstance(tpl string) (*template.Template, error) {
if this.IsCache && this.templateCache[tpl] != nil {
return this.templateCache[tpl], nil
}
var (
t *template.Template
e error
)
t = template.New(path.Base(tpl))
t.Funcs(this.FuncMap)
t, e = t.ParseFiles(path.Join(this.Dir, tpl))
if e != nil {
return nil, e
}
if this.IsCache {
this.templateCache[tpl] = t
}
return t, nil
}
示例9: ParseTemplate
// ParseTemplate loads the requested template along with _base.html, caching
// the result (if configured to do so)
func ParseTemplate(name string, partial bool) (*template.Template, error) {
cachedMutex.Lock()
defer cachedMutex.Unlock()
if t, ok := cachedTemplates[name]; ok {
return t, nil
}
tempPath := strings.Replace(name, "/", string(filepath.Separator), -1)
tempFile := filepath.Join(webConfig.TemplateDir, tempPath)
log.LogTrace("Parsing template %v", tempFile)
var err error
var t *template.Template
if partial {
// Need to get basename of file to make it root template w/ funcs
base := path.Base(name)
t = template.New(base).Funcs(TemplateFuncs)
t, err = t.ParseFiles(tempFile)
} else {
t = template.New("layout.html").Funcs(TemplateFuncs)
// Note that the layout file must be the first parameter in ParseFiles
t, err = t.ParseFiles(filepath.Join(webConfig.TemplateDir, "layout.html"), tempFile)
}
if err != nil {
return nil, err
}
// Allows us to disable caching for theme development
if webConfig.TemplateCache {
if partial {
log.LogTrace("Caching partial %v", name)
cachedTemplates[name] = t
} else {
log.LogTrace("Caching template %v", name)
cachedTemplates[name] = t
}
}
return t, nil
}
示例10: parseFiles
//ParseFiles goes trough a folder (non-recursively), parsing and
//adding all HTML files into a template.
func parseFiles(t *template.Template, dir string) (temp *template.Template, err error) {
f, err := os.Open(dir)
if err != nil {
return
}
fis, err := f.Readdir(0)
if err != nil {
return
}
filenames := make([]string, 0)
for _, fi := range fis {
if fi.IsDir() || getFileType(fi.Name()) != "html" {
continue
}
filenames = append(filenames, dir+string(os.PathSeparator)+fi.Name())
}
temp, err = t.ParseFiles(filenames...)
return
}
示例11: TestApi
testSuite *api.TestSuite
report *api.Report
t *template.Template
)
func TestApi(t *testing.T) {
RegisterFailHandler(Fail)
junitReporter := reporters.NewJUnitReporter("junit.xml")
RunSpecsWithDefaultAndCustomReporters(t, "api Suite", []Reporter{junitReporter})
}
var _ = BeforeSuite(func() {
testSuiteTmp, err := api.ParseJunitXML("sample_junit.xml")
testSuite = testSuiteTmp
Expect(err).Should(BeNil())
report = api.Aggregate(testSuite)
fmap := template.FuncMap{
"formateFloatStr": api.FormateFloatStr,
"isOdd": api.IsOdd,
"resultSymbol": api.ResultSymbol,
}
t = template.New("test").Funcs(fmap)
t = template.Must(t.ParseFiles("../../tmpl/summary.html"))
t = template.Must(t.ParseFiles("../../tmpl/packages.html"))
t = template.Must(t.ParseFiles("../../tmpl/testcase.html"))
t = template.Must(t.ParseFiles("../../tmpl/failure_detail.html"))
})
示例12: main
func main() {
var help bool
var bindto, config_file string
var config_contents []byte
var application_tmpl, memberlist_tmpl, print_tmpl *template.Template
var unique_member_detail_template *template.Template
var authenticator *ancientauth.Authenticator
var debug_authenticator bool
var config membersys.MembersysConfig
var db *membersys.MembershipDB
var err error
flag.BoolVar(&help, "help", false, "Display help")
flag.StringVar(&bindto, "bind", "127.0.0.1:8080",
"The address to bind the web server to")
flag.StringVar(&config_file, "config", "",
"Path to a file containing a MembersysConfig protocol buffer")
flag.BoolVar(&debug_authenticator, "debug-authenticator", false,
"Debug the authenticator?")
flag.Parse()
if help || config_file == "" {
flag.Usage()
os.Exit(1)
}
config_contents, err = ioutil.ReadFile(config_file)
if err != nil {
log.Fatal("Unable to read ", config_file, ": ", err)
}
err = proto.Unmarshal(config_contents, &config)
if err != nil {
err = proto.UnmarshalText(string(config_contents), &config)
}
if err != nil {
log.Fatal("Error parsing ", config_file, ": ", err)
}
// Load and parse the HTML templates to be displayed.
application_tmpl, err = template.ParseFiles(
config.GetTemplateDir() + "/form.html")
if err != nil {
log.Fatal("Unable to parse form template: ", err)
}
print_tmpl, err = template.ParseFiles(
config.GetTemplateDir() + "/printlayout.html")
if err != nil {
log.Fatal("Unable to parse print layout template: ", err)
}
memberlist_tmpl = template.New("memberlist")
memberlist_tmpl.Funcs(fmap)
memberlist_tmpl, err = memberlist_tmpl.ParseFiles(
config.GetTemplateDir() + "/memberlist.html")
if err != nil {
log.Fatal("Unable to parse member list template: ", err)
}
unique_member_detail_template = template.New("memberdetail")
unique_member_detail_template.Funcs(fmap)
unique_member_detail_template, err =
unique_member_detail_template.ParseFiles(
config.GetTemplateDir() + "/memberdetail.html")
if err != nil {
log.Fatal("Unable to parse member detail template: ", err)
}
authenticator, err = ancientauth.NewAuthenticator(
config.AuthenticationConfig.GetAppName(),
config.AuthenticationConfig.GetCertPath(),
config.AuthenticationConfig.GetKeyPath(),
config.AuthenticationConfig.GetCaBundlePath(),
config.AuthenticationConfig.GetAuthServerHost(),
config.AuthenticationConfig.GetX509KeyserverHost(),
int(config.AuthenticationConfig.GetX509CertificateCacheSize()))
if err != nil {
log.Fatal("Unable to assemble authenticator: ", err)
}
if debug_authenticator {
authenticator.Debug()
}
db, err = membersys.NewMembershipDB(
config.DatabaseConfig.GetDatabaseServer(),
config.DatabaseConfig.GetDatabaseName(),
time.Duration(config.DatabaseConfig.GetDatabaseTimeout())*time.Millisecond)
if err != nil {
log.Fatal("Unable to connect to the cassandra DB ",
config.DatabaseConfig.GetDatabaseServer(), " at ",
config.DatabaseConfig.GetDatabaseName(), ": ", err)
}
// Register the URL handlers to be invoked.
http.Handle("/admin/api/members", &MemberListHandler{
admingroup: config.AuthenticationConfig.GetAuthGroup(),
auth: authenticator,
database: db,
pagesize: config.GetResultPageSize(),
//.........这里部分代码省略.........
示例13: Run
func (o *opParseFiles) Run(t *htmlTmpl.Template) (*htmlTmpl.Template, error) {
if t == nil {
return htmlTmpl.ParseFiles(o.files...)
}
return t.ParseFiles(o.files...)
}