當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Template.ParseFiles方法代碼示例

本文整理匯總了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

}
開發者ID:Lao-liu,項目名稱:GoInk,代碼行數:28,代碼來源:view.go

示例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
}
開發者ID:sunfmin,項目名稱:mangotemplate,代碼行數:27,代碼來源:template.go

示例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)
	}
}
開發者ID:RaviTezu,項目名稱:GolangTraining,代碼行數:34,代碼來源:main.go

示例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")
}
開發者ID:NeoChow,項目名稱:qor,代碼行數:12,代碼來源:context.go

示例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...)
}
開發者ID:MrDustpan,項目名稱:go-samples,代碼行數:13,代碼來源:views.go

示例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...)
}
開發者ID:fblecha,項目名稱:fuel,代碼行數:16,代碼來源:run.go

示例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)
	}
}
開發者ID:musicking,項目名稱:qor,代碼行數:44,代碼來源:context.go

示例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
}
開發者ID:vckai,項目名稱:GoAnswer,代碼行數:19,代碼來源:view.go

示例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
}
開發者ID:jmcarbo,項目名稱:smtpd-1,代碼行數:43,代碼來源:template.go

示例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
}
開發者ID:sellweek,項目名稱:TOGY-server,代碼行數:26,代碼來源:util.go

示例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"))
})
開發者ID:wu8685,項目名稱:htmlizer,代碼行數:30,代碼來源:api_suite_test.go

示例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(),
//.........這裏部分代碼省略.........
開發者ID:starshipfactory,項目名稱:membersys,代碼行數:101,代碼來源:memberservice.go

示例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...)
}
開發者ID:orian,項目名稱:template,代碼行數:6,代碼來源:template.go


注:本文中的html/template.Template.ParseFiles方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。