Display Python objects in the web page. * `*values`: Python objects to display. Each object is introspected to determine the appropriate rendering method. * `target`: DOM element ID where content should be displayed. If `None` (default), uses the current script tag's design
(*values, target=None, append=True)
| 205 | |
| 206 | |
| 207 | def display(*values, target=None, append=True): |
| 208 | """ |
| 209 | Display Python objects in the web page. |
| 210 | |
| 211 | * `*values`: Python objects to display. Each object is introspected to |
| 212 | determine the appropriate rendering method. |
| 213 | * `target`: DOM element ID where content should be displayed. If `None` |
| 214 | (default), uses the current script tag's designated output area. This |
| 215 | can start with '#' (which will be stripped for compatibility). |
| 216 | * `append`: If `True` (default), add content to existing output. If |
| 217 | `False`, replace existing content before displaying. |
| 218 | |
| 219 | When used in a worker, `display()` requires an explicit `target` parameter |
| 220 | to identify where content will be displayed. If used on the main thread, |
| 221 | it automatically uses the current `<script>` tag as the target. If the |
| 222 | script tag has a `target` attribute, that element will be used instead. |
| 223 | |
| 224 | A ValueError is raised if a valid target cannot be found for the current |
| 225 | context. |
| 226 | |
| 227 | ```python |
| 228 | from pyscript import display, HTML |
| 229 | |
| 230 | |
| 231 | # Display raw HTML. |
| 232 | display(HTML("<h1>Hello, World!</h1>")) |
| 233 | |
| 234 | # Display in current script's output area. |
| 235 | display("Hello, World!") |
| 236 | |
| 237 | # Display in a specific element. |
| 238 | display("Hello", target="my-div") |
| 239 | |
| 240 | # Replace existing content (note the `#`). |
| 241 | display("New content", target="#my-div", append=False) |
| 242 | |
| 243 | # Display multiple values in the default target. |
| 244 | display("First", "Second", "Third") |
| 245 | ``` |
| 246 | """ |
| 247 | if isinstance(target, str): |
| 248 | # There's a valid target. |
| 249 | target = target[1:] if target.startswith("#") else target |
| 250 | elif is_none(target): |
| 251 | target = current_target() |
| 252 | element = document.getElementById(target) |
| 253 | if is_none(element): |
| 254 | raise ValueError(f"Cannot find element with id='{target}' in the page.") |
| 255 | # If possible, use a script tag's target attribute. |
| 256 | if element.tagName == "SCRIPT" and hasattr(element, "target"): |
| 257 | element = element.target |
| 258 | # Clear before displaying all values when not appending. |
| 259 | if not append: |
| 260 | element.replaceChildren() |
| 261 | # Add each value. |
| 262 | for value in values: |
| 263 | _write_to_dom(element, value, append) |