Rust Playgroundをブログで使う
こんな感じになります。
fn main() { println!("Hello, Rust!"); }上の実行ボタンを押すと、結果が出力されます。
対応方法
-
playground.jsを作成
次の
playground.jsを、publicディレクトリに作成します。- astro.config.mjs
ディレクトリsrc/
- …
ディレクトリpublic/
- playground.js
- …
playground.js // playground.jsfunction setupRustPlaygrounds() {document.querySelectorAll('pre[data-language="rustpg"]').forEach((codeBlock) => {const pre = codeBlock.parentElement;const code = codeBlock.textContent;// ボタン作成const button = document.createElement('button');button.textContent = '▶ 実行';button.style.margin = '8px 0';button.style.padding = '4px 12px';button.style.backgroundColor = '#ea580c';button.style.color = 'white';button.style.border = 'none';button.style.borderRadius = '6px';button.style.cursor = 'pointer';// 出力表示用のプレ要素const output = document.createElement('pre');output.style.background = '#111';output.style.color = '#eee';output.style.padding = '1rem';output.style.borderRadius = '8px';output.style.marginTop = '0.5rem';output.textContent = '(ここに出力されます)';// 実行処理button.onclick = async () => {output.textContent = '実行中...';const response = await fetch('https://play.rust-lang.org/execute', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({channel: 'stable',mode: 'debug',edition: '2021',crateType: 'bin',tests: false,code: code,}),});const result = await response.json();output.textContent = result.success? result.stdout || '(出力なし)': result.stderr || 'エラーが発生しました';};// 挿入pre.parentNode.insertBefore(button, pre.nextSibling);pre.parentNode.insertBefore(output, button.nextSibling);});}// ページロード後に処理window.addEventListener('DOMContentLoaded', setupRustPlaygrounds); -
playground.jsを読み込ませる
astro.config.mjsに次のように追記します。 遅延読み込みさせるため、defer属性をつけます。export default defineConfig({integrations: [starlight({title: '*****',head: [{tag: 'script',attrs: {src: '/playground.js',type: 'text/javascript',defer: true,},},],}),],});