Insane Miner
Insane Miner

Reputation: 140

How to replace {{var}} in an HTML document to a variable using Python 3

How can I put variables from dict into an HTML document?

Like in replace {{variable}} with 1 in the HTML document with Python.

Python code:

def convert_html_to_python(variables={}, code=""):
    ## Stuff with code variable
some_code = """
<!DOCTYPE html>
<html>

<body>
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    {{var}}
</body>
</html>
"""
convert_html_to_python({"var":"1"}, some_code)

Then the Python script converts HTML document to:

<!DOCTYPE html>
<html>

<body>
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    1
</body>
</html>

I want it to be like Django templates. I do not want to use Django or Flask.

Upvotes: 0

Views: 2663

Answers (2)

KetZoomer
KetZoomer

Reputation: 2915

You can use the replace method on the string.

def convert_html_to_python(variables={}, code=""):
    for variable in variables:
        code = code.replace("{{"+str(variable)+"}}", variables[variable])
    return code

some_code = """
<!DOCTYPE html>
<html>

<body>
    <h1>My First Heading</h1>
    <p>My first paragraph.</p>
    {{var}}
</body>
</html>
"""
print(convert_html_to_python({"var":"1"}, some_code))

Upvotes: 2

Ilan Yashuk
Ilan Yashuk

Reputation: 259

Flask and Django comes with a solution for this. You can try reading an HTML file like a string and change it.

For example:

HTML code

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>

Function to add data:

def add_data(data, html_code):
    write_index = html_code.find('</body>') - 1
    html_code = html_code[:write_index] + '\n<h1>' + data + '</h1>\n' + html_code[write_index + 1:]
    print(html_code)

HTML now:

<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<h1>~~data we insert in~~</h1>
</body>
</html>

Upvotes: 1

Related Questions