How to pass variable data from a Python code to HTML in PyScript
PyScript is an open-source framework that allows developers to use Python code in HTML files.
Note: Read more about PyScript here.
We can pass the values of variables declared in Python code written in <py-script> tag. We achieve this by using a PyScript built-in method write().
Syntax
The following is the syntax for using write() in an HTML file.
<py-script>
pyscript.write(idOfHTMLElement, stringToPass)
</py-script>
The pyscript.write() method takes two parameters:
idOfHTMLElement: The HTML element where we want to display your values in HTML.stringToPass: The string we want to pass from Python code to HTML.
Steps
The following are the steps for passing a value from Python to HTML.
First, we need to import PyScript CDN using the
linktag.In the HTML code, assign an
idto the tag where we want to populate with the Python data.Using the
<py-script>tag, write a Python script in the document.After generating the output to display, we pass it to
write()along with theidof the HTML element we want to add the output to.
Example
The following example shows the passing of variable data from Python to Html elements.
Explanation
Lines 3–4: We use the
linktag to link our HTML document to the PyScript CDN so we can import it later.Lined 9–11: We declare paragraph using the
ptag. And in the paragraph, we use a span tag withid“labelTag”.Line 14: We import Python’s
randomlibrary.Line 16-17. Here we define the
generateRandomNumber()function, that generates a random number between 0–9.Line 19: Here, we use
writeand pass itlabelTag, which is theidof the HTML element in which we want to show the output fromgenerateRandomNumber().
Free Resources