Reputation: 663
I am using Go for template evaluation and the following is my use case.
We have our application in which we ask customers to include prefixed-based placeholders along with their text.
E.g.:
my name is {$.PRE.FIRSTNAME}
This will be automatically replaced with their first name, this is just a simple text, there will be more complex text which will be entered by the customer. it can even be a HTML.
following is the code snippet
Over here the first templateText works perfectly file and the second commented one doesn't work. it throws an exception stating a function not defined.
package main
import (
"bytes"
"html/template"
"log"
)
// OuterObject object
type OuterObject struct {
PRE *InnerObject
}
// InnerObject macro object
type InnerObject struct {
FIRSTNAME, LASTNAME string
}
func main() {
// This works perfectly.
templateText := "my name is {$.PRE.FIRSTNAME} "
// templateText := "my name is {$.PRE.FIRSTNAME} ().push(function() { globalAml.display('sss') };"
//
// Above templateText fails with exception :
// function "globalAml" not defined
//
o := &OuterObject{
PRE: &InnerObject{
FIRSTNAME: "fName",
LASTNAME: "lName",
},
}
var doc bytes.Buffer
t, err := template.New("test").Delims("{", "}").Parse(templateText)
if err != nil {
log.Fatal("Error parsing tag", err)
}
err1 := t.Execute(&doc, o)
if err1 != nil {
log.Println("Error Execute tag", err1)
}
log.Println("Final text ", doc.String())
}
Can anyone help me to ignore the method calls and just to replace the prefixed-based placeholders.
Upvotes: 1
Views: 370
Reputation: 663
I was temporarily able to handle this case by changing the code snippet to following :
t, err := template.New("test").Delims("{$", "}").Parse(templateText)
I know this will fail in cases where customer entering a text containing these above delimiters.
Thanks a lot, guys.
Upvotes: 2
Reputation: 545875
Your second substitution fails because {
and }
are the template delimiters. You need to quote them to make this work:
templateText := "my name is {$.PRE.FIRSTNAME} ().push(function() {`{`} globalAml.display('sss') {`}`};"
Upvotes: 0