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.

  1. First, we need to import PyScript CDN using the link tag.

  2. In the HTML code, assign an id to the tag where we want to populate with the Python data.

  3. Using the <py-script> tag, write a Python script in the document.

  4. After generating the output to display, we pass it to write() along with the id of 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.

Generating random integer and passing to html elements

Explanation

  • Lines 3–4: We use the link tag to link our HTML document to the PyScript CDN so we can import it later.

  • Lined 9–11: We declare paragraph using the p tag. And in the paragraph, we use a span tag with id “labelTag”.

  • Line 14: We import Python’s random library.

  • Line 16-17. Here we define thegenerateRandomNumber() function, that generates a random number between 0–9.

  • Line 19: Here, we use write and pass it labelTag, which is the id of the HTML element in which we want to show the output from generateRandomNumber().

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved