File tree Expand file tree Collapse file tree 2 files changed +63
-9
lines changed Expand file tree Collapse file tree 2 files changed +63
-9
lines changed Original file line number Diff line number Diff line change 1- import { loadPyodide } from 'pyodide' ;
1+ import { loadPyodide , type PyodideInterface } from 'pyodide' ;
2+
23
34/**
45 * Set up Pyodide and install pyhtml-enhanced.
56 */
6- export async function pythonInit ( ) {
7- let pyodide = await loadPyodide ( ) ;
7+ async function pyodideInit ( ) {
8+ const pyodide = await loadPyodide ( ) ;
89 await pyodide . loadPackage ( "micropip" ) ;
910 const micropip = pyodide . pyimport ( "micropip" ) ;
1011 await micropip . install ( 'pyhtml-enhanced' ) ;
1112 return pyodide ;
1213}
14+
15+ let pyodide : PyodideInterface ;
16+
17+ export async function getPyodide ( ) {
18+ if ( pyodide ) return pyodide ;
19+ pyodide = await pyodideInit ( ) ;
20+ return pyodide ;
21+ }
22+
23+ export async function evalPyHTML ( pyhtml : string ) : Promise < string > {
24+ const code = `import pyhtml as p
25+ document = ${ pyhtml }
26+ str(document)
27+ ` ;
28+ const pyodide = await getPyodide ( ) ;
29+ return pyodide . runPython ( code ) as string ;
30+ }
Original file line number Diff line number Diff line change 11<script lang =" ts" >
2- import { pythonInit } from ' $lib' ;
2+ import { evalPyHTML , getPyodide } from ' $lib' ;
3+ import { onMount } from ' svelte' ;
34
4- const pyodide = pythonInit ();
5+ let pyhtmlCode = $state (`
6+ p.html(
7+ p.head(
8+ p.title("Hello, world!"),
9+ ),
10+ p.body(
11+ p.h1("Hello, world!"),
12+ p.p("This content is being dynamically generated using PyHTML!"),
13+ ),
14+ )
15+ ` .trim ());
16+
17+ let htmlCode = $state (' ' );
18+
19+ async function renderHtml() {
20+ htmlCode = await evalPyHTML (pyhtmlCode );
21+ }
22+
23+ let pyodideReady = $state (false );
24+
25+ onMount (async () => {
26+ await getPyodide ();
27+ console .log (' Pyodide is ready' );
28+ renderHtml ();
29+ pyodideReady = true ;
30+ });
531 </script >
632
733<h1 >Test out PyHTML</h1 >
834
9- {#await pyodide }
10- <p >Pyodide is loading...</p >
11- {:then pyodide }
35+ {#if pyodideReady }
1236 <p >Pyodide loaded successfully!</p >
13- {/await }
37+ <textarea name ="" id ="" bind:value ={pyhtmlCode } oninput ={renderHtml }>
38+ </textarea >
39+
40+ <pre >
41+ <code >
42+ {htmlCode }
43+ </code >
44+ </pre >
45+
46+ <iframe srcdoc ={htmlCode } title =" PyHTML preview" frameborder =" 0" ></iframe >
47+ {:else }
48+ <p >Pyodide is loading...</p >
49+ {/if }
You can’t perform that action at this time.
0 commit comments