0

I have set up a webserver with Micropython as decribed here. In the tutorial, there is an html variable that I am trying to externalize into a separate file and then read it in like so:

import codecs
with codecs.open("main.html", 'r') as f:
    html = f.read()

In principle this works nicely, there is just one flaw. The html variable declaration has a variable called gpio_state inside it, like this:

html = """---html code stuff---""" + gpio_state + """---more html stuff---"""

The gpio_state variable resolves into ON or OFF when I have this in the .py file directly as intended. When the html is in a different file and imported with the above method it is read as a string instead. I see gpio_state and the """ characters in my browser.

Is it possible to import an html file with a variable in the python script?

Sorry - I probably lack some python vocabulary here and could have expressed the problem more concisely!

1 Answer 1

1

This would probably be described as reading a template, and replacing the variable parts in it. There are probably some libraries to do templating, but in MicroPython a small solution is probably enough for you.

After reading the file into a variable, you have a string, so you can use the built-in string methods such as replace(look-for, replace-with). Eg:

html2 = html.replace("gpio_state", gpio_state)

You probably shouldn't have the """ string delimiters at the start and end of the file, since this is not part of the html. Typically, in templating systems, some special character sequence is used to delimit the variable parts from the html, eg <?gpio_state?>, but if you prefer you can keep to """ + gpio_state + """, if this is unlikely to occur in the real html part.

Sign up to request clarification or add additional context in comments.

1 Comment

I tried <? and other escape characters but could not find any that did the trick. The string method is a nice workaroud. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.