当前位置: 首页>>代码示例>>Golang>>正文


Golang template.URL函数代码示例

本文整理汇总了Golang中html/template.URL函数的典型用法代码示例。如果您正苦于以下问题:Golang URL函数的具体用法?Golang URL怎么用?Golang URL使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了URL函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ReverseUrl

// 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
}
开发者ID:ericcapricorn,项目名称:revel,代码行数:30,代码来源:template.go

示例2: subjectGroupPage

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
	}

}
开发者ID:andrewcharlton,项目名称:school-dashboard,代码行数:59,代码来源:subjectgroups.go

示例3: staticFileFn

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)
}
开发者ID:jmcvetta,项目名称:gddo,代码行数:8,代码来源:template.go

示例4: Home

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
	}
}
开发者ID:pombredanne,项目名称:Go-Package-Store,代码行数:10,代码来源:github.go

示例5: HomePage

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
	}
}
开发者ID:leobcn,项目名称:Go-Package-Store,代码行数:10,代码来源:github.go

示例6: AttendanceGroups

// 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)
		}
	}
}
开发者ID:andrewcharlton,项目名称:school-dashboard,代码行数:57,代码来源:attendance.go

示例7: submissionsAddHandler

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)
}
开发者ID:rojters,项目名称:gopherpods,代码行数:54,代码来源:gopherpods.go

示例8: UserEditPage

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)
	}
}
开发者ID:cswank,项目名称:quimby,代码行数:52,代码来源:admin.go

示例9: addTabletLinks

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()))
	}
}
开发者ID:chinna1986,项目名称:vitess,代码行数:15,代码来源:plugin_zktopo.go

示例10: initialize

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)
}
开发者ID:hugoduncan,项目名称:hugo,代码行数:34,代码来源:site.go

示例11: LargeGraph

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()))
}
开发者ID:KirillShaman,项目名称:nsq,代码行数:28,代码来源:graphs.go

示例12: Sparkline

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()))
}
开发者ID:KirillShaman,项目名称:nsq,代码行数:26,代码来源:graphs.go

示例13: init

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)
}
开发者ID:bertzzie,项目名称:obrolansubuh-backend,代码行数:33,代码来源:init.go

示例14: Image

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"
}
开发者ID:leobcn,项目名称:Go-Package-Store,代码行数:7,代码来源:github.go

示例15: doTestShortcodeCrossrefs

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)
	}
}
开发者ID:vincentsys,项目名称:hugo,代码行数:33,代码来源:embedded_shortcodes_test.go


注:本文中的html/template.URL函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。