Creating code blocks with dataviewjs

What I’m trying to do

I’d like to be able to generate code blocks from dataviewjs.
i.e. generating the exact same output as something like:

print("Hello, World!")

The documentation lists a few methods like header or paragraph, but nothing for code blocks.

Things I have tried

I’ve tried creating a simple code block:

dv.el('code', 'print("Hello, World!")', { cls: 'language-python' });

I also tried replicated the HTML output of a code block:

const txt = 'print("Hello, World!")';

let pre = dv.el('pre', null, { cls: 'language-python', attr: { tabindex: '0' } });

const code = `<code class="language-python is-loaded">${txt}</code><button class="copy-code-button">Copy</button>`;
pre.innerHTML = code;

But both end up with outputs that don’t look the same as a regular code block.

Does anyone know a better way to do this?

What about:

dv.paragraph('~~~python\nprint("Hello, World!")\n~~~')

Thank you! This did the trick.
It seems like I was overthinking it.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.