func slashPie(c *gin.Context) { group := c.Param("group") if _, err := os.Stat(path.Join(RuntimeArgs.SourcePath, group+".db")); os.IsNotExist(err) { c.HTML(http.StatusOK, "login.tmpl", gin.H{ "ErrorMessage": "First download the app or CLI program to insert some fingerprints.", }) return } network := c.Param("network") location := c.Param("location") ps, _ := openParameters(group) vals := []int{} names := []string{} fmt.Println(ps.Results[network].Guess[location]) for guessloc, val := range ps.Results[network].Guess[location] { names = append(names, guessloc) vals = append(vals, val) } namesJSON, _ := json.Marshal(names) valsJSON, _ := json.Marshal(vals) c.HTML(http.StatusOK, "pie.tmpl", gin.H{ "Names": template.JS(namesJSON), "Vals": template.JS(valsJSON), }) }
func userAsJavascript(user *slack.User) template.JS { jsonProfile, err := json.MarshalIndent(user, "", " ") if err != nil { return template.JS(`{"error": "couldn't decode user"}`) } return template.JS(jsonProfile) }
func renderArticle(c interface{}, path string, arg string) { // inject content stylePath := resolveFilename("style.css") coverPath := resolveFilename("_cover") styleContent, _ := ioutil.ReadFile(stylePath) coverJSON, _ := ioutil.ReadFile(coverPath) article := readArticle(path) data := gin.H{ "title": filepath.Base(path), "article": template.JS(article.data), "useMathjax": article.useMathjax, "style": template.CSS(styleContent), "cover": template.JS(coverJSON), } switch target := c.(type) { case *gin.Context: // arg is the template used target.HTML(http.StatusOK, arg, data) case *template.Template: // arg is the file to be written to w, err := createFile(arg) if err != nil { panic(err.Error()) } target.Execute(w, data) } }
func init() { var err error rand.Seed(time.Now().UnixNano()) // funcMap contains the functions available to the view template funcMap := template.FuncMap{ // totals sums all the exercises in []RepData "totals": func(d []RepData) int { return totalReps(d) }, // allow easy converting of strings to JS string (turns freqData{{ OfficeName}}: freqData"OC" -> freqDataOC in JS) "js": func(s string) template.JS { return template.JS(s) }, // d3ChartData correctly formats []RepData to the JS format so data can display "d3ChartData": func(d []RepData) template.JS { parts := make([]string, len(d)) for i, data := range d { parts[i] = fmt.Sprintf("{State:'%s',freq:{pull_up:%d, sit_up:%d, push_up: %d, squat:%d}}", data.Date, data.ExerciseCounts[PullUps], data.ExerciseCounts[SitUps], data.ExerciseCounts[PushUps], data.ExerciseCounts[Squats], ) } return template.JS(strings.Join(parts, ",\n")) }, // d3ChartDataForOffice is a helper method to avoid complexities with nesting ranges in the template "d3ChartDataForOffice": func(officeName string, reps map[string][]RepData) template.JS { // TODO: DRY up with ^^ parts := make([]string, len(reps[officeName])) for i, data := range reps[officeName] { parts[i] = fmt.Sprintf("{State:'%s',freq:{pull_up:%d, sit_up:%d, push_up: %d, squat:%d}}", data.Date, data.ExerciseCounts[PullUps], data.ExerciseCounts[SitUps], data.ExerciseCounts[PushUps], data.ExerciseCounts[Squats], ) } return template.JS(strings.Join(parts, ",\n")) }, } // parse tempaltes in init so we don't have to parse them on each request // pro: single parsing // con: have to restart the process to load file changes ViewTemplate, err = template.New("view.html").Funcs(funcMap).ParseFiles(filepath.Join("go_templates", "view.html")) if err != nil { log.Fatalln(err) } IndexTemplate, err = template.New("index.html").Funcs(funcMap).ParseFiles(filepath.Join("go_templates", "index.html")) if err != nil { log.Fatalln(err) } }
// jsDate formats a date as Date.UTC javascript call. func jsDate(v interface{}) template.JS { if t, ok := v.(time.Time); ok && !t.IsZero() { return template.JS(fmt.Sprintf("Date.UTC(%d, %d, %d, %d, %d, %d)", t.Year(), t.Month()-1, t.Day(), t.Hour(), t.Minute(), t.Second())) } else { return template.JS("null") } }
func ArticleHandler(c *gin.Context, articlePath, filename string) { article := readArticle(filename) c.HTML(http.StatusOK, "editor.html", gin.H{ "title": articlePath, "article": template.JS(article.data), "useMathjax": true, // always load mathjax for editor "saveURL": template.JS(_path.Join("/api/save", articlePath)), }) }
func WebThingTable(w http.ResponseWriter, r *http.Request) { thing := context.Get(r, ContextKeyThing).(*Thing) account := context.Get(r, ContextKeyAccount).(*Account) if !thing.EditableById(account.Character) { http.Error(w, "No access to table data", http.StatusForbidden) return } if r.Method == "POST" { updateText := r.PostFormValue("updated_data") var updates map[string]interface{} err := json.Unmarshal([]byte(updateText), &updates) if err != nil { // aw carp // TODO: set a flash? http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } deleteText := r.PostFormValue("deleted_data") var deletes map[string]interface{} err = json.Unmarshal([]byte(deleteText), &deletes) if err != nil { // aw carp // TODO: set a flash? http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } thing.Table = mergeMapInto(updates, thing.Table) thing.Table = deleteMapFrom(deletes, thing.Table) World.SaveThing(thing) http.Redirect(w, r, fmt.Sprintf("%stable", thing.GetURL()), http.StatusSeeOther) return } RenderTemplate(w, r, "thing/page/table.html", map[string]interface{}{ "Title": fmt.Sprintf("Edit all data – %s", thing.Name), "Thing": thing, "json": func(v interface{}) interface{} { output, err := json.MarshalIndent(v, "", " ") if err != nil { escapedError := template.JSEscapeString(err.Error()) message := fmt.Sprintf("/* error encoding JSON: %s */ {}", escapedError) return template.JS(message) } return template.JS(output) }, }) }
func (webapp *Webapp) getEnabledPluginsJS() template.JS { out := make(map[string]bool) for _, pluginName := range webapp.enabledPlugins { out[pluginName] = true } jsonMap, err := json.MarshalIndent(out, "", " ") if err != nil { log.Println("Couldn't marshal EnabledPlugins list for rendering", err) return template.JS("{}") } return template.JS(jsonMap) }
func RenderTemplate(path string, input []byte, metadata map[string]interface{}) []byte { R := func(relativeFilename string) string { filename := filepath.Join(filepath.Dir(path), relativeFilename) return string(RenderTemplate(filename, Read(filename), metadata)) } importhtml := func(relativeFilename string) template.HTML { return template.HTML(R(relativeFilename)) } importcss := func(relativeFilename string) template.CSS { return template.CSS(R(relativeFilename)) } importjs := func(relativeFilename string) template.JS { return template.JS(R(relativeFilename)) } templateName := Relative(*sourceDir, path) funcMap := template.FuncMap{ "importhtml": importhtml, "importcss": importcss, "importjs": importjs, "sorted": SortedValues, } tmpl, err := template.New(templateName).Funcs(funcMap).Parse(string(input)) if err != nil { Fatalf("Render Template %s: Parse: %s", path, err) } output := bytes.Buffer{} if err = tmpl.Execute(&output, metadata); err != nil { Fatalf("Render Template %s: Execute: %s", path, err) } return output.Bytes() }
func (p *Pivot) chartData(opts *ChartOptions) template.JS { if p.Rows.ColumnLen() != 1 || p.Cols.ColumnLen() != 1 { return "" } xaxis := p.Cols.ColumnIndex(0) labels := p.Rows.ColumnIndex(0) var series []string for i := 0; i < labels.Len(); i++ { var data, name template.JS if xaxis.Type() == Time { data = jsDateArray(xaxis.Values(), p.Data[i]) } else { data = jsArray(p.Data[i]) } if l := labels.Index(i); l == nil { name = js("NULL") } else { name = js(l) } var yaxis, charttype string if opts != nil { if isElement(string(name), opts.Rightaxis) { yaxis = ", yAxis: 1" } if isElement(string(name), opts.Column) { charttype = ", type: 'column'" } else if isElement(string(name), opts.Line) { charttype = ", type: 'line'" } } series = append(series, fmt.Sprintf("{name: %s, data: %s%s%s}", name, data, yaxis, charttype)) } return template.JS("[" + strings.Join(series, ", ") + "]") }
func (this *accountC) ApplyCash(ctx *web.Context) { p := this.GetPartner(ctx) conf := this.GetSiteConf(p.Id) m := this.GetMember(ctx) _, w := ctx.Request, ctx.ResponseWriter acc, err := goclient.Member.GetMemberAccount(m.Id, m.DynamicToken) bank, err := goclient.Member.GetBankInfo(m.Id, m.DynamicToken) if err != nil { w.Write([]byte("error:" + err.Error())) return } js, _ := json.Marshal(bank) ctx.App.Template().Execute(w, gof.TemplateDataMap{ "conf": conf, "record": 15, "partner": p, "member": m, "account": acc, "entity": template.JS(js), }, "views/ucenter/account/apply_cash.html", "views/ucenter/inc/header.html", "views/ucenter/inc/menu.html", "views/ucenter/inc/footer.html") }
// makeBugChomperPage builds and serves the BugChomper page. func makeBugChomperPage(w http.ResponseWriter, r *http.Request) { // Redirect for login if needed. user := login.LoggedInAs(r) if user == "" { http.Redirect(w, r, login.LoginURL(w, r), http.StatusFound) return } glog.Infof("Logged in as %s", user) issueTracker := issue_tracker.New(login.GetHttpClient(r)) w.Header().Set("Content-Type", "text/html") glog.Info("Loading bugs for " + user) bugList, err := issueTracker.GetBugs(PROJECT_NAME, user) if err != nil { reportError(w, err.Error(), http.StatusInternalServerError) return } bugsById := make(map[string]*issue_tracker.Issue) bugsByPriority := make(map[string][]*issue_tracker.Issue) for _, bug := range bugList.Items { bugsById[strconv.Itoa(bug.Id)] = bug var bugPriority string for _, label := range bug.Labels { if strings.HasPrefix(label, PRIORITY_PREFIX) { bugPriority = label[len(PRIORITY_PREFIX):] } } if _, ok := bugsByPriority[bugPriority]; !ok { bugsByPriority[bugPriority] = make( []*issue_tracker.Issue, 0) } bugsByPriority[bugPriority] = append( bugsByPriority[bugPriority], bug) } bugsJson, err := json.Marshal(bugsById) if err != nil { reportError(w, err.Error(), http.StatusInternalServerError) return } data := struct { Title string User string BugsJson template.JS BugsByPriority *map[string][]*issue_tracker.Issue Priorities []string PriorityPrefix string }{ Title: "BugChomper", User: user, BugsJson: template.JS(string(bugsJson)), BugsByPriority: &bugsByPriority, Priorities: issue_tracker.BugPriorities, PriorityPrefix: PRIORITY_PREFIX, } if err := templates.ExecuteTemplate(w, "bug_chomper.html", data); err != nil { reportError(w, err.Error(), http.StatusInternalServerError) return } }
func UUIDRender(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) // call mongo and lookup the redirection to use... session, err := services.GetMongoCon() if err != nil { panic(err) } defer session.Close() // Optional. Switch the session to a monotonic behavior. session.SetMode(mgo.Monotonic, true) c := session.DB("test").C("schemaorg") c2 := session.DB("test").C("csvwmeta") // Get the schema.org data URI := fmt.Sprintf("http://opencoredata.org/id/dataset/%s", vars["UUID"]) result := SchemaOrgMetadata{} err = c.Find(bson.M{"url": URI}).One(&result) if err != nil { log.Printf("URL lookup error: %v", err) } // context setting hack // result.Context = ` "opencore": "http://opencoredata.org/voc/1/", "glview": "http://geolink.org/view/1/", "schema": "http://schema.org/"` result.Context = "http://schema.org" jsonldtext, _ := json.MarshalIndent(result, "", " ") // results as embeddale JSON-LD // Get the CSVW data result2 := CSVWMeta{} err = c2.Find(bson.M{"url": URI}).One(&result2) if err != nil { log.Printf("URL lookup error: %v", err) } // result.Context = ` "opencore": "http://opencoredata.org/voc/1/", "glview": "http://geolink.org/view/1/", "schema": "http://schema.org/"` // needs to be: "@context": ["http://www.w3.org/ns/csvw", {"@language": "en"}], result2.Context = "http://www.w3.org/ns/csvw" csvwtext, _ := json.MarshalIndent(result2, "", " ") // results as embeddale JSON-LD ht, err := template.New("some template").ParseFiles("templates/jrso_dataset_new.html") //open and parse a template text file if err != nil { log.Printf("template parse failed: %s", err) } // need a simple function call to extract the "janus" keyword from the keyword string and toLower it and // pass it in this struct to use in the data types web component measureString := getJanusKeyword(result.Keywords) dataForTemplate := TemplateForDoc{Schema: result, CSVW: result2, Schemastring: template.JS(string(jsonldtext)), Csvwstring: template.JS(string(csvwtext)), MeasureType: measureString, UUID: vars["UUID"]} err = ht.ExecuteTemplate(w, "T", dataForTemplate) //substitute fields in the template 't', with values from 'user' and write it out to 'w' which implements io.Writer if err != nil { log.Printf("htemplate execution failed: %s", err) } // go get the CSVW metadata and inject the whole package and the rendered table }
func projDat(db repodb.DB, c *context, route *repoRoute) ( interface{}, error, ) { repo := route.Repo() b, err := db.LatestBuild(repo) if err != nil { return nil, err } type d struct { GoImport string UserInfo *userInfo Repo string RepoUser string RepoName string Dirs []string Commit string Proj template.JS } return &d{ GoImport: route.goImportMeta(), UserInfo: newUserInfo(c), Repo: repo, RepoUser: route.owner, RepoName: route.repo, Commit: shortCommit(b.Build), Proj: template.JS(string(b.Struct)), }, nil }
func (c *Chart) JS() (template.JS, error) { js, err := json.Marshal(c) if err != nil { return "", err } return template.JS(js), nil }
//修改门店信息 func (this *shopC) Create(ctx *web.Context) { ctx.App.Template().Execute(ctx.Response, gof.TemplateDataMap{ "entity": template.JS("{}"), }, "views/partner/shop/create.html") }
func (up *GoogleUserProfile) AsJavascript() template.JS { jsonProfile, err := json.MarshalIndent(up, "", " ") if err != nil { log.Fatal("Couldn't unmarshal Cookie with GoogleUserProfile in there", err) } return template.JS(jsonProfile) }
func (tss TimeSeriesSlice) C3Time() template.JS { step, ok := tss.checkEqualStep() if !ok { panic("step sizes don't match") } start, end := tss.getStartEnd() s := bytes.NewBufferString("[ 'x', ") for cursor := start; cursor.Before(end); cursor = cursor.Add(step) { if err := s.WriteByte('\''); err != nil { panic(err) } if _, err := s.WriteString(cursor.Format("20060102 15:04:05")); err != nil { panic(err) } if _, err := s.WriteString("',"); err != nil { panic(err) } } if s.Len() > 0 { s.Truncate(s.Len() - 1) } if err := s.WriteByte(']'); err != nil { panic(err) } return template.JS(s.String()) }
func init() { HtmlFuncBoot.Register(func(w *Web) { // HTML Marksafe w.HtmlFunc["html"] = func(str string) html.HTML { return html.HTML(str) } // HTML Attr MarkSafe w.HtmlFunc["htmlattr"] = func(str string) html.HTMLAttr { return html.HTMLAttr(str) } // JS Marksafe w.HtmlFunc["js"] = func(str string) html.JS { return html.JS(str) } // JS String Marksafe w.HtmlFunc["jsstr"] = func(str string) html.JSStr { return html.JSStr(str) } // CSS Marksafe w.HtmlFunc["css"] = func(str string) html.CSS { return html.CSS(str) } }) }
// jsDateArray formats a pair of slices as JavaScript array of 2-elem arrays. func jsDateArray(dates, values []interface{}) template.JS { var r []string for i := range dates { r = append(r, fmt.Sprintf("[%s, %s]", jsDate(dates[i]), js(values[i]))) } return template.JS("[" + strings.Join(r, ", ") + "]") }
// jsArray formats an slice as an array of javascript values. // Each value should be one of bool, int64, float64, time.Time or string func jsArray(data []interface{}) template.JS { var r []string for _, v := range data { r = append(r, string(js(v))) } return template.JS("[" + strings.Join(r, ", ") + "]") }
func (p Point) JSDate() template.JS { // Use Unix time because Date(yy,mm,dd...) constructor assumes // the arguments are local time, and we don't know what time zone // the eventual viewer of the web page is in. Using Unix time gives // the correct instant and then displays in the local time zone. return template.JS(fmt.Sprintf("new Date(%d)", p.Time.UnixNano()/1e6)) }
func (this *MainController) Get() { this.Data["Css"] = conf.GetCss() this.Data["Js"] = conf.GetJs() user := models.NewUser() err := user.FindById(int(1)) if err != nil { beego.Error(err) return } data, err := user.GetInitialData() if err != nil { beego.Error(err) } str, err := json.Marshal(map[string]interface{}{"init": data}) if err != nil { beego.Error(err) } this.Data["Storage"] = template.JS(string(str)) this.TplNames = "/index.tpl" return }
func createLiveBlogSample(newStatus int, timestamp time.Time, firstBlogID string, originSource string, page Page) LiveBlogSample { if newStatus > len(blogs) { newStatus = len(blogs) } blogItems := getBlogEntries(newStatus, timestamp) score := createScore(newStatus, 0) firstItemIndex := getBlogEntryIndexFromID(firstBlogID, blogItems) lenghtCurrentPageBlog := int(math.Min(float64(len(blogItems)), float64(firstItemIndex+MAX_BLOG_ITEMS_NUMBER_PER_PAGE))) urlPrefix := buildPrefixPaginationURL(originSource, page) nextPageId := getNextPageId(blogItems, firstItemIndex+MAX_BLOG_ITEMS_NUMBER_PER_PAGE) previousPageId := getPrevPageId(firstItemIndex) nextPageUrl := buildPaginationURL(urlPrefix, nextPageId) prevPageUrl := buildPaginationURL(urlPrefix, previousPageId) disabled := "" if prevPageUrl != "" { disabled = "disabled" } blogMetadata, _ := json.MarshalIndent(createMetadata(originSource), " ", " ") return LiveBlogSample{BlogItems: blogItems[firstItemIndex:lenghtCurrentPageBlog], FootballScore: score, BlogMetadata: template.JS(blogMetadata), NextPageURL: nextPageUrl, PrevPageURL: prevPageUrl, PageNumber: getPageNumberFromProductIndex(firstItemIndex), Disabled: template.HTMLAttr(disabled)} }
func (t *Template) render(rctx core.RenderContext) string { b := &bytes.Buffer{} // Update functions for current rendering context. t.tmpl.Funcs(map[string]interface{}{ "slot": func(name, elt string) template.HTML { s := t.node.Slot(name) if elt == "" { return template.HTML(s.Node().Render(rctx)) } return template.HTML(fmt.Sprintf("<%s id='%s'>%s</%s>", elt, s.ID(), s.Node().Render(rctx), elt)) }, "event": func(name string) template.JS { return template.JS(fmt.Sprintf("stdweb.events.onClick('%s', '%s', event)", template.JSEscapeString(t.node.ID()), template.JSEscapeString(name))) }, }) err := t.tmpl.Execute(b, &tplData{ ID: t.node.ID(), RunID: rctx.RunID(), UpdateID: rctx.UpdateID(), Data: t.data, }) if err == nil { return b.String() } return html.EscapeString(err.Error()) }
// 强制序列化为可用于HTML的JSON func MustHtmlJson(v interface{}) template.JS { d, err := json.Marshal(v) if err != nil { log.Println("[ Go2o][ Json] - ", err.Error()) } return template.JS(d) }
func (set FlightSnapshotSet) ToJSVar() template.JS { str := "{\n" for i, fs := range set { str += fmt.Sprintf(" %d: %s,\n", i, fs.ToJSString()) } str += " }\n" return template.JS(str) }
func (j *JQueryDataTable) JS() template.JS { bytes, _ := json.Marshal(j) // fmt.Println("string:",string(bytes)) // fmt.Println("html:", template.HTML( string(bytes))) // fmt.Println("HTMLEscapeString:", template.HTMLEscapeString( string(bytes))) return template.JS(bytes) }
// ParseTemplate parses the template text and prepares it to be instantiated on // specific nodes. func ParseTemplate(text string) (*ParsedTemplate, error) { // Use fake functions just to make sure that the parser knows about them. t, err := template.New("foo").Funcs(map[string]interface{}{ "slot": func(name string) template.HTML { return template.HTML("") }, "event": func(name string) template.JS { return template.JS("") }, }).Parse(text) return (*ParsedTemplate)(t), err }
func thJsonify(v interface{}) html.JS { bs, err := json.Marshal(v) assert(err) buf := new(bytes.Buffer) json.HTMLEscape(buf, bs) return html.JS(buf.String()) }