Set CodeBlock Language in Tiptap Editor

September 21, 2024

How to set CodeBlock language in Tiptap editor.

The following function can be attached to a button to set current CodeBlock element language.

function setCodeBlockLanguage() {
  let attrs = editor.getAttributes('codeBlock');
  let userVal = window.prompt('Language', attrs.language);
  if (userVal === null) return;
  
  editor.commands.setCodeBlock({
    language: userVal
  })
}

Above code will prompt for code language and set language- class for the <code> element, for example:

<pre>
  <code class="language-html"> console.log(1000); </code>
</pre>

Detail

Get current language attributes value:

let attrs = editor.getAttributes('codeBlock');
console.log(attrs.language);

Set the language attribute to CodeBlock element.

editor.commands.setCodeBlock({
  language: attrs.language
});

Links

Editorial:

blog-posts [workspace]: vanillawebdev/tiptap-editor/codeblock-set-language.html

Comments

Thank You

for your visit