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)
}
To print a variable's name: Split the string on the equal sign and get the variable's name. Use the print() function to print the variable's name.
You can refer to the name of a variable to access its value. The value of a variable can be changed throughout your program. Variables are declared using this syntax: name = value. Python variables are useful because they allow you to reduce the need to repeat the same value in your code.
You cannot do such stuff. The slice does not contain the variables but their values, so you cannot get their name. Just use a map.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With