Ejemplo n.º 1
0
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

}
Ejemplo n.º 2
0
// 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
}
Ejemplo n.º 3
0
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)
	}
}
Ejemplo n.º 4
0
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")
}
Ejemplo n.º 5
0
// 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...)
}
Ejemplo n.º 6
0
Archivo: run.go Proyecto: fblecha/fuel
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...)
}
Ejemplo n.º 7
0
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)
	}
}
Ejemplo n.º 8
0
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
}
Ejemplo n.º 9
0
// 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
}
Ejemplo n.º 10
0
//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
}
Ejemplo n.º 11
0
	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"))
})
Ejemplo n.º 12
0
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(),
	})

	http.Handle("/admin/api/applicants", &ApplicantListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/queue", &MemberQueueListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/dequeue", &MemberDeQueueListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/trash", &MemberTrashListHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
		pagesize:   config.GetResultPageSize(),
	})

	http.Handle("/admin/api/accept", &MemberAcceptHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/reject", &MemberRejectHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/editfee", &MemberFeeHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/agreement-upload", &MemberAgreementUploadHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/cancel-queued", &MemberQueueCancelHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/goodbye-member", &MemberGoodbyeHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin/api/member", &MemberDetailHandler{
		admingroup: config.AuthenticationConfig.GetAuthGroup(),
		auth:       authenticator,
		database:   db,
	})

	http.Handle("/admin", &TotalListHandler{
		admingroup:           config.AuthenticationConfig.GetAuthGroup(),
		auth:                 authenticator,
		database:             db,
		pagesize:             config.GetResultPageSize(),
		template:             memberlist_tmpl,
		uniqueMemberTemplate: unique_member_detail_template,
	})

	http.HandleFunc("/barcode", MakeBarcode)

	http.Handle("/", &FormInputHandler{
		applicationTmpl: application_tmpl,
		database:        db,
		passthrough:     http.FileServer(http.Dir(config.GetTemplateDir())),
		printTmpl:       print_tmpl,
		useProxyRealIP:  config.GetUseProxyRealIp(),
	})

	err = http.ListenAndServe(bindto, nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Ejemplo n.º 13
0
func (o *opParseFiles) Run(t *htmlTmpl.Template) (*htmlTmpl.Template, error) {
	if t == nil {
		return htmlTmpl.ParseFiles(o.files...)
	}
	return t.ParseFiles(o.files...)
}