示例#1
0
// Return a url capable of invoking a given controller method:
// "Application.ShowApp 123" => "/app/123"
func ReverseUrl(args ...interface{}) (template.URL, error) {
	if len(args) == 0 {
		return "", fmt.Errorf("no arguments provided to reverse route")
	}

	action := args[0].(string)
	if action == "Root" {
		return template.URL(AppRoot), nil
	}
	actionSplit := strings.Split(action, ".")
	if len(actionSplit) != 2 {
		return "", fmt.Errorf("reversing '%s', expected 'Controller.Action'", action)
	}

	// Look up the types.
	var c Controller
	if err := c.SetAction(actionSplit[0], actionSplit[1]); err != nil {
		return "", fmt.Errorf("reversing %s: %s", action, err)
	}

	// Unbind the arguments.
	argsByName := make(map[string]string)
	for i, argValue := range args[1:] {
		Unbind(argsByName, c.MethodType.Args[i].Name, argValue)
	}

	return template.URL(MainRouter.Reverse(args[0].(string), argsByName).Url), nil
}
func subjectGroupPage(e env.Env, w http.ResponseWriter, r *http.Request) {

	if redir := checkRedirect(e, w, r, 2); redir {
		return
	}
	header(e, w, r, 2)
	defer footer(e, w, r)

	path := strings.Split(r.URL.Path, "/")
	subjID, err := strconv.Atoi(path[3])
	if err != nil {
		fmt.Fprintf(w, "Error: %v", err)
		return
	}
	subj := e.Subjects[subjID]

	f := getFilter(e, r)
	g, err := e.GroupByFilteredClass(path[3], "", f)
	if err != nil {
		fmt.Fprintf(w, "Error: %v", err)
	}

	classes, err := e.Classes(path[3], f.Date)
	if err != nil {
		fmt.Fprintf(w, "Error: %v", err)
	}
	sort.Sort(sort.StringSlice(classes))

	clsGrps := []subGroup{}
	for _, c := range classes {
		grp := g.SubGroup(group.Class(subj.Subj, c))
		if len(grp.Students) > 0 {
			clsGrps = append(clsGrps, subGroup{c, template.URL(c), grp})
		}
	}

	data := struct {
		Query     template.URL
		Year      string
		Subj      *subject.Subject
		SubGroups []subGroup
		Matrix    subGroupMatrix
		Classes   []subGroup
	}{
		template.URL(r.URL.RawQuery),
		f.Year,
		subj,
		subGroups(g),
		groupMatrix(g),
		clsGrps,
	}

	err = e.Templates.ExecuteTemplate(w, "subjectgroups.tmpl", data)
	if err != nil {
		fmt.Fprintf(w, "Error: %v", err)
		return
	}

}
示例#3
0
文件: template.go 项目: jmcvetta/gddo
func staticFileFn(p string) htemp.URL {
	h, err := fileHashFn("static/" + p)
	if err != nil {
		log.Printf("WARNING could not read static file %s, %v", p, err)
		return htemp.URL("/-/static/" + p)
	}
	return htemp.URL("/-/static/" + p + "?v=" + h)
}
示例#4
0
func (p githubPresenter) Home() *template.URL {
	switch {
	case strings.HasPrefix(p.repo.Root, "github.com/"):
		url := template.URL("https://github.com/" + p.ghOwner + "/" + p.ghRepo)
		return &url
	default:
		url := template.URL("http://" + p.repo.Root)
		return &url
	}
}
示例#5
0
func (this gitHubPresenter) HomePage() *template.URL {
	switch goPackage := this.repo.GoPackages()[0]; {
	case strings.HasPrefix(goPackage.Bpkg.ImportPath, "github.com/"):
		url := template.URL("https://github.com/" + this.gitHubOwner + "/" + this.gitHubRepo)
		return &url
	default:
		url := template.URL("http://" + goPackage.Bpkg.ImportPath)
		return &url
	}
}
// AttendanceGroups produces a page with attendance summaries for the
// various student groups.
func AttendanceGroups(e env.Env) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		if redir := checkRedirect(e, w, r, 0); redir {
			return
		}
		header(e, w, r, 0)
		defer footer(e, w, r)

		f := getFilter(e, r)
		g, err := e.GroupByFilter(f)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
			return
		}

		type YearGroup struct {
			Name   string
			Query  template.URL
			Groups []subGroup
			Matrix subGroupMatrix
		}

		// Ignore error - will appear as blank string anyway
		week, _ := e.CurrentWeek()

		data := struct {
			Week       string
			Query      template.URL
			YearGroups []YearGroup
		}{
			week,
			template.URL(r.URL.RawQuery),
			[]YearGroup{{"All Years", template.URL(""), subGroups(g), groupMatrix(g)}},
		}

		for year := 7; year < 15; year++ {
			y := g.SubGroup(group.Year(year))
			if len(y.Students) == 0 {
				continue
			}
			yeargroup := YearGroup{fmt.Sprintf("Year %v", year),
				template.URL(fmt.Sprintf("&year=%v", year)),
				subGroups(y),
				groupMatrix(y)}
			data.YearGroups = append(data.YearGroups, yeargroup)

		}

		err = e.Templates.ExecuteTemplate(w, "attendancegroups.tmpl", data)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
		}
	}
}
示例#7
0
func submissionsAddHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		serveErr(ctx, err, w)
		return
	}

	ID, _, err := datastore.AllocateIDs(ctx, "Podcast", nil, 1)
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	date, err := time.Parse(yyyymmdd, r.FormValue("date"))
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	podcast := Podcast{
		ID:         ID,
		Show:       r.FormValue("show"),
		Title:      r.FormValue("title"),
		Desc:       r.FormValue("desc"),
		URL:        template.URL(r.FormValue("url")),
		MediaURL:   template.URL(r.FormValue("media_url")),
		RuntimeSec: r.FormValue("runtime"),
		Size:       r.FormValue("size"),
		Date:       date,
		Added:      time.Now(),
	}

	if _, err := datastore.Put(ctx, datastore.NewKey(ctx, "Podcast", "", ID, nil), &podcast); err != nil {
		serveErr(ctx, err, w)
		return
	}

	key, err := datastore.DecodeKey(r.FormValue("key"))
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	if err := datastore.Delete(ctx, key); err != nil {
		serveErr(ctx, err, w)
		return
	}

	if err := memcache.Delete(ctx, cacheKey); err != nil {
		log.Errorf(ctx, "memcache delete error %v", err)
	}

	successTmpl.ExecuteTemplate(w, "base", nil)
}
示例#8
0
文件: admin.go 项目: cswank/quimby
func UserEditPage(w http.ResponseWriter, req *http.Request) {
	args := handlers.GetArgs(req)
	username := args.Vars["username"]
	page := editUserPage{
		userPage: userPage{
			User:  args.User.Username,
			Admin: handlers.Admin(args),
		},
		Permissions: []string{"read", "write", "admin"},
	}
	if username == "new-user" {
		page.Links = []link{
			{"quimby", "/"},
			{"admin", "/admin.html"},
			{"new user", "/admin/users/new-user"},
		}
		page.Actions = []action{
			{Name: "cancel", URI: template.URL("/admin.html"), Method: "get"},
		}
		page.End = 0
	} else {
		u := quimby.NewUser(username, quimby.UserDB(args.DB))
		if err := u.Fetch(); err != nil {
			context.Set(req, "error", err)
			return
		}

		q := url.Values{}
		q.Add("resource", fmt.Sprintf("/admin/users/%s", username))
		q.Add("name", username)
		page.EditUser = u
		page.Links = []link{
			{"quimby", "/"},
			{"admin", "/admin.html"},
			{u.Username, fmt.Sprintf("/admin/users/%s", u.Username)},
		}
		page.Actions = []action{
			{Name: "cancel", URI: template.URL("/admin.html"), Method: "get"},
			{Name: "delete", URI: template.URL(fmt.Sprintf("/admin/confirmation?%s", q.Encode())), Method: "get"},
			{Name: "update-password", URI: template.URL(fmt.Sprintf("/admin/users/%s/password", username)), Method: "get"},
			{Name: "update-tfa", URI: template.URL(fmt.Sprintf("/admin/users/%s/tfa", username)), Method: "post"},
		}

		page.End = 3
	}

	if username == "new-user" {
		templates["new-user.html"].template.ExecuteTemplate(w, "base", page)
	} else {
		templates["edit-user.html"].template.ExecuteTemplate(w, "base", page)
	}
}
示例#9
0
func (ex ZkExplorer) addTabletLinks(data string, result *ZkResult) {
	t := &topo.Tablet{}
	err := json.Unmarshal([]byte(data), t)
	if err != nil {
		return
	}

	if port, ok := t.Portmap["vt"]; ok {
		result.Links["status"] = template.URL(fmt.Sprintf("http://%v:%v/debug/status", t.Hostname, port))
	}

	if !t.Parent.IsZero() {
		result.Links["parent"] = template.URL(fmt.Sprintf("/zk/%v/vt/tablets/%v", t.Parent.Cell, t.Parent.TabletUidStr()))
	}
}
示例#10
0
文件: site.go 项目: hugoduncan/hugo
func (s *Site) initialize() {
	site := s

	s.checkDirectories()

	walker := func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			PrintErr("Walker: ", err)
			return nil
		}

		if fi.IsDir() {
			site.Directories = append(site.Directories, path)
			return nil
		} else {
			if ignoreDotFile(path) {
				return nil
			}
			site.Files = append(site.Files, path)
			return nil
		}
	}

	filepath.Walk(s.absContentDir(), walker)

	s.Info = SiteInfo{
		BaseUrl: template.URL(s.Config.BaseUrl),
		Title:   s.Config.Title,
		Recent:  &s.Pages,
		Config:  &s.Config,
	}

	s.Shortcodes = make(map[string]ShortcodeFunc)
}
示例#11
0
func (g *GraphOptions) LargeGraph(gr GraphTarget, key string) template.URL {
	params := url.Values{}
	params.Set("height", "450")
	params.Set("width", "800")
	params.Set("bgcolor", "ff000000") // transparent
	params.Set("fgcolor", "999999")
	params.Set("yMin", "0")
	params.Set("lineMode", "connected")
	params.Set("drawNullAsZero", "false")

	interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
	targets, color := gr.Target(key)
	for _, target := range targets {
		target = fmt.Sprintf(target, g.Prefix(gr.Host(), metricType(key)))
		target = fmt.Sprintf(`summarize(%s,"%s","avg")`, target, interval)
		if metricType(key) == "counter" {
			scale := fmt.Sprintf("%.04f", 1/float64(*statsdInterval/time.Second))
			target = fmt.Sprintf(`scale(%s,%s)`, target, scale)
		}
		log.Println("Adding target: ", target)
		params.Add("target", target)
	}
	params.Add("colorList", color)

	params.Set("from", g.GraphInterval.GraphFrom)
	params.Set("until", g.GraphInterval.GraphUntil)
	return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
示例#12
0
func (g *GraphOptions) Sparkline(gr GraphTarget, key string) template.URL {
	params := url.Values{}
	params.Set("height", "20")
	params.Set("width", "120")
	params.Set("hideGrid", "true")
	params.Set("hideLegend", "true")
	params.Set("hideAxes", "true")
	params.Set("bgcolor", "ff000000") // transparent
	params.Set("fgcolor", "black")
	params.Set("margin", "0")
	params.Set("yMin", "0")
	params.Set("lineMode", "connected")
	params.Set("drawNullAsZero", "false")

	interval := fmt.Sprintf("%dsec", *statsdInterval/time.Second)
	targets, color := gr.Target(key)
	for _, target := range targets {
		target = fmt.Sprintf(target, g.Prefix(gr.Host(), metricType(key)))
		params.Add("target", fmt.Sprintf(`summarize(%s,"%s","avg")`, target, interval))
	}
	params.Add("colorList", color)

	params.Set("from", g.GraphInterval.GraphFrom)
	params.Set("until", g.GraphInterval.GraphUntil)
	return template.URL(fmt.Sprintf("%s/render?%s", g.GraphiteUrl, params.Encode()))
}
示例#13
0
func init() {
	// Filters is the default set of global filters.
	revel.Filters = []revel.Filter{
		revel.PanicFilter,             // Recover from panics and display an error page instead.
		revel.RouterFilter,            // Use the routing table to select the right Action
		revel.FilterConfiguringFilter, // A hook for adding or removing per-Action filters.
		revel.ParamsFilter,            // Parse parameters into Controller.Params.
		revel.SessionFilter,           // Restore and write the session cookie.
		revel.FlashFilter,             // Restore and write the flash cookie.
		revel.ValidationFilter,        // Restore kept validation errors and save new ones from cookie.
		revel.I18nFilter,              // Resolve the requested language
		HeaderFilter,                  // Add some security based headers
		revel.InterceptorFilter,       // Run interceptors around the action.
		revel.CompressFilter,          // Compress the result.
		revel.ActionInvoker,           // Invoke the action.
	}

	// A template function we built because Polymer's iron-icon uses ":"
	// in its icon attribute value. ":" will be parsed as escaped content
	// by go's html/template.
	//
	// We choose template.URL because:
	// 1. You can insert a link in the property, and
	// 2. a ":" for defaults like "editor:publish" will work.
	revel.TemplateFuncs["polymer_icon"] = func(attr string) template.URL {
		return template.URL(attr)
	}

	// register startup functions with OnAppStart
	// ( order dependent )
	// revel.OnAppStart(InitDB)
	// revel.OnAppStart(FillCache)
}
示例#14
0
func (this gitHubPresenter) Image() template.URL {
	// Use the repo owner avatar image.
	if user, _, err := gh.Users.Get(this.gitHubOwner); err == nil && user.AvatarURL != nil {
		return template.URL(*user.AvatarURL)
	}
	return "https://github.com/images/gravatars/gravatar-user-420.png"
}
示例#15
0
func doTestShortcodeCrossrefs(t *testing.T, relative bool) {
	var refShortcode string
	var expectedBase string

	if relative {
		refShortcode = "relref"
		expectedBase = "/bar"
	} else {
		refShortcode = "ref"
		expectedBase = baseURL
	}

	path := filepath.FromSlash("blog/post.md")
	in := fmt.Sprintf(`{{< %s "%s" >}}`, refShortcode, path)
	expected := fmt.Sprintf(`%s/simple/url/`, expectedBase)

	templ := tpl.New()
	p, _ := pageFromString(simplePageWithURL, path)
	p.Node.Site = &SiteInfo{
		Pages:   &(Pages{p}),
		BaseURL: template.URL(helpers.SanitizeURLKeepTrailingSlash(baseURL)),
	}

	output, err := HandleShortcodes(in, p, templ)

	if err != nil {
		t.Fatal("Handle shortcode error", err)
	}

	if output != expected {
		t.Errorf("Got\n%q\nExpected\n%q", output, expected)
	}
}
// AttainmentGroups produces a page with a summary of the
// attainment of each subgroup
func AttainmentGroups(e env.Env) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		if redir := checkRedirect(e, w, r, 1); redir {
			return
		}
		header(e, w, r, 1)
		defer footer(e, w, r)

		f := getFilter(e, r)
		g, err := e.GroupByFilter(f)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
			return
		}

		data := struct {
			Query  template.URL
			Groups []subGroup
		}{
			template.URL(r.URL.RawQuery),
			subGroups(g),
		}

		err = e.Templates.ExecuteTemplate(w, "attainmentgroups.tmpl", data)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
		}
	}
}
// AttendanceExplorer provides a page for exploring the attendance figures
// in more detail, and examine individual students.
func AttendanceExplorer(e env.Env) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		if redir := checkRedirect(e, w, r, 2); redir {
			return
		}

		header(e, w, r, 2)
		defer footer(e, w, r)

		f := getFilter(e, r)
		g, err := e.GroupByFilter(f)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
			return
		}

		week, _ := e.CurrentWeek()

		data := struct {
			Query template.URL
			Week  string
			Group group.Group
		}{
			template.URL(r.URL.RawQuery),
			week,
			g,
		}

		err = e.Templates.ExecuteTemplate(w, "attendance.tmpl", data)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
		}
	}
}
示例#18
0
func SOPC2PParentHandler(w http.ResponseWriter, r *http.Request) {
	DontCache(&w)

	vars := mux.Vars(r)
	documentDomain := vars["documentDomain"]
	childSrcBase64 := vars["childSrcBase64"]

	// Setting document.domain to "" is different to not setting it at all, hence
	// the "none" case
	var script template.HTML
	if documentDomain == "none" {
		script = template.HTML("<script></script>")
	} else {
		script = template.HTML("<script>document.domain = \"" + documentDomain + "\";</script>")
	}

	childSrc, err := base64.StdEncoding.DecodeString(childSrcBase64)
	if err != nil {
		log.Println(err)
		return
	}

	p := &C2PParentPage{Script: script,
		ChildSrc: template.URL(childSrc)}
	t, err := template.ParseFiles("./sop/c2p_parent.html")
	if err != nil {
		log.Println(err)
	}
	t.Execute(w, p)
}
示例#19
0
文件: handlers.go 项目: husio/bb
// Without return URL query string from wrapped Request with given keys removed
func (b URLQueryBuilder) Without(keys ...string) template.URL {
	q := b.Request.URL.Query()
	for _, k := range keys {
		delete(q, k)
	}
	return template.URL(q.Encode())
}
示例#20
0
// encodeFilter back to a query string
func encodeFilter(f database.Filter) template.URL {

	query := fmt.Sprintf("natyear=%v&date=%v&resultset=%v", f.NatYear, f.Date, f.Resultset)
	if f.Year != "" {
		query += "&year=" + f.Year
	}
	if f.PP != "" {
		query += "&pp=" + f.PP
	}
	if f.EAL != "" {
		query += "&eal=" + f.EAL
	}
	if f.Gender != "" {
		query += "&gender=" + f.Gender
	}
	if len(f.SEN) > 0 && !(len(f.SEN) == 1 && f.SEN[0] == "") {
		for _, s := range f.SEN {
			query += "&sen=" + s
		}
	}
	if len(f.KS2Bands) > 0 && !(len(f.KS2Bands) == 1 && f.KS2Bands[0] == "") {
		for _, k := range f.KS2Bands {
			query += "&ks2band=" + k
		}
	}
	if len(f.Ethnicities) > 0 && !(len(f.Ethnicities) == 1 && f.Ethnicities[0] == "") {
		for _, e := range f.Ethnicities {
			query += "&ethnicity=" + e
		}
	}

	return template.URL(query)
}
示例#21
0
func (s *Site) initialize() {
	site := s

	s.checkDirectories()

	walker := func(path string, fi os.FileInfo, err error) error {
		if err != nil {
			PrintErr("Walker: ", err)
			return nil
		}

		if fi.IsDir() {
			site.Directories = append(site.Directories, path)
			return nil
		} else {
			site.Files = append(site.Files, path)
			return nil
		}
		return nil
	}

	filepath.Walk(s.c.GetAbsPath(s.c.SourceDir), walker)

	s.Info = SiteInfo{BaseUrl: template.URL(s.c.BaseUrl), Title: s.c.Title}

	s.Shortcodes = make(map[string]ShortcodeFunc)
}
示例#22
0
// MakeTreePage makes directory listings from within git repositories.
// It writes the webpage to the provided http.ResponseWriter.
func MakeTreePage(w http.ResponseWriter, pageinfo *gitPage, g *git, ref, file string) (err error, status int) {
	// Retrieve the list of files from the repository.
	files := g.GetDir(ref, file)

	// If there are no files, return an error.
	if len(files) == 0 {
		return notFound, http.StatusNotFound
	} // Otherwise, continue as normal.

	pageinfo.List = make([]*dirList, len(files))
	for n, f := range files {
		d := &dirList{
			URL:  template.URL(f),
			Name: f,
		}

		var t string
		if strings.HasSuffix(f, "/") {
			t = "tree"
		} else {
			t = "blob"
		}
		d.Link = prefix + pageinfo.Path + t + "/" + path.Join(file, f)
		pageinfo.List[n] = d
	}

	// We return 500 here because the error will only be reported
	// if t.ExecuteTemplate() results in an error.
	return t.ExecuteTemplate(w, "tree.html", pageinfo),
		http.StatusInternalServerError
}
示例#23
0
文件: site.go 项目: maruel/hugo
func (s *Site) initializeSiteInfo() {
	params := viper.GetStringMap("Params")

	permalinks := make(PermalinkOverrides)
	for k, v := range viper.GetStringMapString("Permalinks") {
		permalinks[k] = PathPattern(v)
	}

	s.Info = SiteInfo{
		BaseURL:               template.URL(helpers.SanitizeURLKeepTrailingSlash(viper.GetString("BaseURL"))),
		Title:                 viper.GetString("Title"),
		Author:                viper.GetStringMap("author"),
		Social:                viper.GetStringMapString("social"),
		LanguageCode:          viper.GetString("languagecode"),
		Copyright:             viper.GetString("copyright"),
		DisqusShortname:       viper.GetString("DisqusShortname"),
		GoogleAnalytics:       viper.GetString("GoogleAnalytics"),
		RSSLink:               s.permalinkStr(viper.GetString("RSSUri")),
		BuildDrafts:           viper.GetBool("BuildDrafts"),
		canonifyURLs:          viper.GetBool("CanonifyURLs"),
		preserveTaxonomyNames: viper.GetBool("PreserveTaxonomyNames"),
		Pages:      &s.Pages,
		Menus:      &s.Menus,
		Params:     params,
		Permalinks: permalinks,
		Data:       &s.Data,
	}
}
示例#24
0
func newGitHubPresenter(repo *pkg.Repo, ghOwner, ghRepo string) presenter.Presenter {
	p := &githubPresenter{
		repo:    repo,
		ghOwner: ghOwner,
		ghRepo:  ghRepo,

		image: "https://github.com/images/gravatars/gravatar-user-420.png", // Default fallback.
	}

	// This might take a while.
	if cc, _, err := gh.Repositories.CompareCommits(ghOwner, ghRepo, repo.Local.Revision, repo.Remote.Revision); err == nil {
		p.cc = cc
	} else if rateLimitErr, ok := err.(*github.RateLimitError); ok {
		p.setFirstError(rateLimitError{rateLimitErr})
	} else {
		p.setFirstError(fmt.Errorf("gh.Repositories.CompareCommits: %v", err))
	}

	// Use the repo owner avatar image.
	if user, _, err := gh.Users.Get(ghOwner); err == nil && user.AvatarURL != nil {
		p.image = template.URL(*user.AvatarURL)
	} else if rateLimitErr, ok := err.(*github.RateLimitError); ok {
		p.setFirstError(rateLimitError{rateLimitErr})
	} else {
		p.setFirstError(fmt.Errorf("gh.Users.Get: %v", err))
	}

	return p
}
示例#25
0
func submitAddHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	if err := r.ParseForm(); err != nil {
		serveErr(ctx, err, w)
		return
	}

	success, err := recaptchaCheck(ctx, r.FormValue("g-recaptcha-response"), r.RemoteAddr)
	if err != nil {
		serveErr(ctx, err, w)
		return
	}

	if !success {
		log.Warningf(ctx, "reCAPTCHA check failed")
		failedTmpl.ExecuteTemplate(w, "base", nil)
		return
	}

	sub := Submission{
		URL:       template.URL(strings.TrimSpace(r.FormValue("url"))),
		Submitted: time.Now(),
	}

	if _, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, "Submission", nil), &sub); err != nil {
		serveErr(ctx, err, w)
		return
	}

	thanksTmpl.ExecuteTemplate(w, "base", nil)
}
示例#26
0
文件: site.go 项目: dunn/hugo
func (s *Site) initializeSiteInfo() {
	params := viper.GetStringMap("Params")

	permalinks := make(PermalinkOverrides)
	for k, v := range viper.GetStringMapString("Permalinks") {
		permalinks[k] = PathPattern(v)
	}

	s.Info = SiteInfo{
		BaseUrl:         template.URL(helpers.SanitizeUrlKeepTrailingSlash(viper.GetString("BaseUrl"))),
		Title:           viper.GetString("Title"),
		Author:          viper.GetStringMap("author"),
		LanguageCode:    viper.GetString("languagecode"),
		Copyright:       viper.GetString("copyright"),
		DisqusShortname: viper.GetString("DisqusShortname"),
		BuildDrafts:     viper.GetBool("BuildDrafts"),
		canonifyUrls:    viper.GetBool("CanonifyUrls"),
		Pages:           &s.Pages,
		Recent:          &s.Pages,
		Menus:           &s.Menus,
		Params:          params,
		Permalinks:      permalinks,
		Data:            &s.Data,
	}
}
// Search returns a student search page
func Search(e env.Env) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		if redir := checkRedirect(e, w, r, 0); redir {
			return
		}
		header(e, w, r, 0)
		defer footer(e, w, r)

		name := r.URL.Query().Get("name")

		f := getFilter(e, r)
		g, err := e.Search(name, f)

		data := struct {
			Query template.URL
			Name  string
			Group group.Group
		}{
			template.URL(r.URL.RawQuery),
			name,
			g,
		}

		err = e.Templates.ExecuteTemplate(w, "studentsearch.tmpl", data)
		if err != nil {
			fmt.Fprintf(w, "Error: %v", err)
		}
	}
}
示例#28
0
文件: utils.go 项目: azadi/check
func FuncMap(domain *gettext.Domain) template.FuncMap {
	return template.FuncMap{
		"UnEscaped": func(x string) interface{} {
			return template.HTML(x)
		},
		"UnEscapedURL": func(x string) interface{} {
			return template.URL(x)
		},
		"GetText": func(lang string, text string) string {
			return domain.GetText(lang, text)
		},
		"Equal": func(one string, two string) bool {
			return one == two
		},
		"Not": func(b bool) bool {
			return !b
		},
		"And": func(a bool, b bool) bool {
			return a && b
		},
		"UserManual": func(lang string) string {
			if _, ok := HaveManual[lang]; !ok {
				lang = "en"
			}
			return lang
		},
	}
}
示例#29
0
func (ar ActionRepository) PopulateTabletActions(actions map[string]template.URL, alias string) {
	for name := range ar.tabletActions {
		values := url.Values{}
		values.Set("action", name)
		values.Set("alias", alias)
		actions[name] = template.URL("/tablet_actions?" + values.Encode())
	}
}
示例#30
0
// subGroups returns a list of subgroups to be analysed.
func subGroups(g group.Group) []subGroup {

	groups := []subGroup{}
	for _, def := range groupDefs {
		groups = append(groups, subGroup{def.Name, template.URL(def.Query), g.SubGroup(def.Filter)})
	}
	return groups
}