本文整理汇总了Golang中html/template.JS函数的典型用法代码示例。如果您正苦于以下问题:Golang JS函数的具体用法?Golang JS怎么用?Golang JS使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了JS函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: userAsJavascript
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)
}
示例2: renderArticle
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)
}
}
示例3: init
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)
}
}
示例4: jsDate
// 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")
}
}
示例5: ArticleHandler
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)),
})
}
示例6: WebThingTable
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)
},
})
}
示例7: getEnabledPluginsJS
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)
}
示例8: RenderTemplate
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()
}
示例9: chartData
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, ", ") + "]")
}
示例10: ApplyCash
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")
}
示例11: makeBugChomperPage
// 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
}
}
示例12: UUIDRender
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
}
示例13: projDat
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
}
示例14: JS
func (c *Chart) JS() (template.JS, error) {
js, err := json.Marshal(c)
if err != nil {
return "", err
}
return template.JS(js), nil
}
示例15: Create
//修改门店信息
func (this *shopC) Create(ctx *web.Context) {
ctx.App.Template().Execute(ctx.Response,
gof.TemplateDataMap{
"entity": template.JS("{}"),
},
"views/partner/shop/create.html")
}