本文整理汇总了Golang中text/template.JSEscapeString函数的典型用法代码示例。如果您正苦于以下问题:Golang JSEscapeString函数的具体用法?Golang JSEscapeString怎么用?Golang JSEscapeString使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了JSEscapeString函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestEscapge
func TestEscapge() {
str := template.HTMLEscapeString("<br>hello</br>")
fmt.Println(str)
jsStr := template.JSEscapeString("<script>alert('123')</script>")
fmt.Println(jsStr)
}
示例2: printError
// printError prints err to Stderr with options. If browserErrors is non-nil, errors are also written for presentation in browser.
func printError(err error, options *gbuild.Options, browserErrors *bytes.Buffer) {
e := sprintError(err)
options.PrintError("%s\n", e)
if browserErrors != nil {
fmt.Fprintln(browserErrors, `console.error("`+template.JSEscapeString(e)+`");`)
}
}
示例3: UpdateDirectList
// UpdateBlockedList updates the list of hosts that are not going through any
// proxy.
func UpdateDirectList(hosts []string) {
var escaped []string
for _, v := range hosts {
escaped = append(escaped, template.JSEscapeString(v))
}
dl := strings.Join(escaped, "\",\n\"")
pac.dLRWMutex.Lock()
pac.directList = dl
pac.dLRWMutex.Unlock()
}
示例4: makeBody
func makeBody(query string, minutes int) (string, error) {
const elkBodyTemplate = `{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "{{.Query}}"
}
},
"filter": {
"bool": {
"must": [
{
"range": {
"@timestamp": {
"gte": "now-{{.Minutes}}m"
}
}
}
],
"must_not": []
}
}
}
},
"size": 500,
"sort": {
"@timestamp": "desc"
},
"fields": [
"_source"
],
"script_fields": {},
"fielddata_fields": [
"timestamp",
"@timestamp"
]
}'
`
tmpl, err := template.New("body").Parse(elkBodyTemplate)
if err != nil {
return "", fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
templateData := elkBodyTemplateData{template.JSEscapeString(query), fmt.Sprintf("%d", minutes)}
var b bytes.Buffer
err = tmpl.Execute(&b, templateData)
if err != nil {
return "", fmt.Errorf("Failed to parse elk template: %s\n", fmt.Sprint(err))
}
return b.String(), nil
}
示例5: init
func init() {
var select_handler_template_string string
{
buf := bytes.NewBuffer(nil)
form_body := `<form action="/expand/{{.Name}}" method="get">
<fieldset>
<legend>Description</legend>
<p>{{.Description}}</p>
</fieldset>{{range .Inputs}}
<fieldset>
<legend>{{.}}</legend>
<input type="button" value="+{{.}}" class="add" onclick="AddRemoveableFieldHelper($(this), '{{js .}}')" />
</fieldset>{{end}}
<div>
<button type="submit">Expand</button>
</div>
</form>`
field_adder_helper := `<script type="text/javascript">
function AddRemoveableFieldHelper(self, name) {
AddRemoveableField(self.parent(), [
"` + template.JSEscapeString(`<input type="text" class="field" name="`) + `" + name + "` + template.JSEscapeString(`" cols="80"/>`) + `",
"` + template.JSEscapeString(`<input type="button" class="remove" value="-" onclick="$(this).parent().remove()"/>`) + `",
]);
}
</script>`
form := prettyTemplateData{
Title: `Expand Template`,
Scripts: []string{field_adder_script, field_adder_helper},
Body: []string{form_body},
}
if err := pretty_html_template.Execute(buf, form); err != nil {
panic(err)
}
select_handler_template_string = buf.String()
}
template.Must(select_handler_template.Parse(select_handler_template_string))
}
示例6: WriteJson
//json接口返回
func (ctx *Context) WriteJson(content []byte) error {
ctx.Output.Header("Content-Type", "application/x-javascript; charset=utf-8")
ctx.Output.Status = 200
callback := template.JSEscapeString(ctx.Input.Query("_callback"))
if len(callback) > 0 {
bt := bytes.NewBufferString(" " + callback)
bt.WriteString("(")
bt.Write(content)
bt.WriteString(");\r\n")
ctx.Output.Body(bt.Bytes())
} else {
ctx.Output.Body(content)
}
return nil
}
示例7: UpdateBlockedList
// UpdateBlockedList updates the list of hosts that are going through the
// blocked proxy configuration.
func UpdateBlockedList(hosts ...[]string) {
var allHosts []string
allHosts = append(allHosts, "alkasir.com")
for _, h := range hosts {
allHosts = append(allHosts, h...)
}
var escaped []string
for _, v := range allHosts {
escaped = append(escaped, template.JSEscapeString(v))
}
dl := strings.Join(escaped, "\",\n\"")
pac.dLRWMutex.Lock()
pac.blockedList = dl
pac.dLRWMutex.Unlock()
}
示例8: jsonExtendedMarshal
// jsonExtendedMarshal encodes a currency into a JSON array: [1234.56, "€", "1.234,56 €"]
func jsonExtendedMarshal(c *Money) ([]byte, error) {
if c == nil || c.Valid == false {
return nullString, nil
}
var b bytes.Buffer
b.WriteRune('[')
b.Write(c.Ftoa())
b.WriteString(`, "`)
b.WriteString(template.JSEscapeString(string(c.Symbol())))
b.WriteString(`", "`)
lb, err := c.Localize()
if err != nil {
if PkgLog.IsDebug() {
PkgLog.Debug("money.jsonExtendedMarshal.Localize", "err", err, "currency", c, "bytes", lb)
}
return nil, errgo.Mask(err)
}
template.JSEscape(&b, lb)
b.WriteRune('"')
b.WriteRune(']')
return b.Bytes(), err
}
示例9: JSEscapeString
// JSEscapeString returns the escaped JavaScript equivalent of the plain text data s.
func JSEscapeString(s string) string {
return template.JSEscapeString(s)
}
示例10: JSONError
// JSONError is a helper function to write json error message to http.ResponseWriter
func JSONError(rw http.ResponseWriter, message string, code int) {
rw.WriteHeader(code)
rw.Write([]byte(`{"error":"` + template.JSEscapeString(message) + `"}`))
}
示例11: translate
// translate translates the Go expression.
func (e *expression) translate(expr ast.Expr) {
switch typ := expr.(type) {
// godoc go/ast ArrayType
// Lbrack token.Pos // position of "["
// Len Expr // Ellipsis node for [...]T array types, nil for slice types
// Elt Expr // element type
case *ast.ArrayType:
// Type checking
if _, ok := typ.Elt.(*ast.Ident); ok {
if e.tr.getExpression(typ.Elt).hasError {
return
}
}
if typ.Len == nil { // slice
break
}
e.tr.arrays[e.tr.funcId][e.tr.blockId][e.tr.lastVarName] = void
if _, ok := typ.Len.(*ast.Ellipsis); ok {
e.zero, _ = e.tr.zeroValue(true, typ.Elt)
e.isEllipsis = true
break
}
if !e.isMultiDim {
e.WriteString("g.MkArray([")
} else {
e.WriteString(",")
}
e.WriteString(e.tr.getExpression(typ.Len).String())
e.tr.isArray = true
switch t := typ.Elt.(type) {
case *ast.ArrayType: // multi-dimensional array
e.isMultiDim = true
e.translate(typ.Elt)
case *ast.Ident, *ast.StarExpr: // the type is initialized
e.zero, _ = e.tr.zeroValue(true, typ.Elt)
e.WriteString(fmt.Sprintf("],%s", SP+e.zero))
default:
panic(fmt.Sprintf("*expression.translate: type unimplemented: %T", t))
}
// godoc go/ast BasicLit
// Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING
// Value string // literal string
case *ast.BasicLit:
if typ.Value[0] == '`' { // raw string literal
typ.Value = template.JSEscapeString(typ.Value)
typ.Value = `"` + typ.Value[1:len(typ.Value)-1] + `"`
}
// Replace new lines
if strings.Contains(typ.Value, "\\n") {
typ.Value = strings.Replace(typ.Value, "\\n", Char['\n'], -1)
}
// Replace tabulators
if strings.Contains(typ.Value, "\\t") {
typ.Value = strings.Replace(typ.Value, "\\t", Char['\t'], -1)
}
e.WriteString(typ.Value)
e.isBasicLit = true
// http://golang.org/doc/go_spec.html#Comparison_operators
// https://developer.mozilla.org/en/JavaScript/Reference/Operators/Comparison_Operators
//
// godoc go/ast BinaryExpr
// X Expr // left operand
// Op token.Token // operator
// Y Expr // right operand
case *ast.BinaryExpr:
var isBitwise, isComparing, isOpNot bool
addSpaces := true
op := typ.Op.String()
switch typ.Op {
case token.NEQ:
isOpNot = true
fallthrough
case token.EQL:
isComparing = true
// Bitwise operators
case token.AND_NOT:
op = "&~"
fallthrough
case token.AND, token.OR, token.XOR:
isBitwise = true
addSpaces = false
case token.SHL, token.SHR:
addSpaces = false
}
if addSpaces {
op = SP + op + SP
}
if e.tr.isConst {
//.........这里部分代码省略.........
示例12: clean
func clean(str string) string {
return template.JSEscapeString(template.HTMLEscapeString(str))
}
示例13: directiveEscapeJsString
func directiveEscapeJsString(value data.Value, _ []data.Value) data.Value {
return data.String(template.JSEscapeString(value.String()))
}