I'm trying to build an easy to use templating system. Basically I just want to create a slice with different variables ( strings ) and then loop through the slice and replace the markup {{}}
with the actual values. So if the variable 'name
' is onevar
it will look in the template for {{onevar}}
and replace that with the actual value of the variable .
Question: how do I get the variable name? Basically what's in the source code. Is it possible ? I've tried something with reflect but seems I couldn't get it right. See belowg
onevar := "something"
other := "something else"
var msg string
sa := []string{onevar, other}
for _, v := range sa {
vName := reflect.TypeOf(v).Name()
vName = fmt.Sprintf("{{%s}}", vName)
msg = strings.Replace(msg, vName, v, -1)
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…