Hello!
I am building a website generation engine. In it I have html strings that also contain variable names. I want to replace the variable names with other data and I am trying to do that using replace.
Here is a simplified excerpt from the code:
# translation engine
def trans(string, translations):
for key, value in translations.items():
string = string.replace(key, str(value))
return string
# html formatting variable
pg = '<div class="content">$variable</div>'
# content variables
variable = ''
description = 'ABC'
find_on_map = ''
# translation dictionary
place_hold_repl = {'$description': description, '$find_on_map': find_on_map, '$variable': variable}
# variable for testing
variable = 'abcdef'
# calling translation
find_on_map = trans(pg, place_hold_repl)
print(find_on_map)
Actual result: <div class="content"></div>
Expected result: <div class="content">abcdef</div>
I must have misunderstood something because the variable names are replaced, but with nothing instead of the variable values. It is as if it uses the variable content like it was when the placeholder dictionary was created. If so, is there a way to have it use the variable contents as they are at the time of calling the translation function without moving the dictonary down the code? Or perhaps an even better way to do the whole thing?
Best regards, Niklas