Forum Archive

Replacing place holder with variable content using replace

Niklas

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

Niklas

After having thought about this some more, I think it might be better to re-structure the script and do it another way instead. 🙂

mikael

@Niklas, for future reference:

  • You cannot assign a value of a variable as a value in dictionary, then change the value of the variable and expect the value in the dictionary also to change.
  • There is stdlib class string.Template that does exactly what you were attempting, even with the same $variable syntax.
  • Pythonista also includes the jinja2 templating engine used by e.g. Django. It lets you write templates like this:
{% extends "layout.html" %}
{% block body %}
  <ul>
  {% for user in users %}
    <li><a href="{{ user.url }}">{{ user.username }}</a></li>
  {% endfor %}
  </ul>
{% endblock %}
Niklas

Thank you, that was very helpful! 😀 👍🏻