pythonhtmlpyscriptpyodide

PyScript: running code blocks in between paragraphs in HTML?


I've been looking for a way to run interactive python code blocks on my personal website, and PyScript looked to be a good solution. However, it seems like PyScript is currently designed to always output at the end of HTML tags, rather than in between sections of HTML code.

<script defer src="https://pyscript.net/latest/pyscript.js"></script>
<div>   
    <div>
    <py-env>
        <py-script src="indexcode.py" std-out="output">
        </py-script>
    </py-env>
    </div>
</div>

<div id="output"></div>

<p>This is a block of HTML</p>


In the code above, I tried to define a separate tag to take the output of my PyScript code using the std-out attribute, but this doesn't seem to affect the position of the output, (where the code is outputted, then the "This is a block of HTML" section follows.)

Screenshot of resulting code on my website

I'm wondering if there's any good solution to this? None of the examples on PyScript's website had anything close to this. I understand that PyScript's relatively new, so it's possible that this just isn't a feature yet.


Solution

  • PyScript introduces a new "built-in" function (i.e. a function you do not need to import) called display() for this use case, of sending text content to the page. display() takes an optional keyword argument called target, which specifies the ID of a DOM element to write the content to. If target is not specified, the content appears as a child element of the current <py-script> (or <py-repl>) tag.

    <div id="verytop"></div>
    
    <p>AAA</p>
    
    <py-script>
        display("One")
    </py-script>
    
    <p>BBB</p>
    
    <py-script>
        display("Two")
    </py-script>
    
    <p>CCC</p>
    
    <py-script>
        display("Up Top", target="verytop")
    </py-script>
    

    The output order is then:

    Up Top
    AAA
    One
    BBB
    Two
    CCC