Code

Syntax-highlighted code cards with language variants, custom content, and optional copy buttons.

Code cards

Blue blocks show usage code; dark blocks are live component examples.

Display source using the same compact code block as this documentation, with the standard card border radius and an optional copy icon in the top-right corner. CodeCard uses Prism with the documentation’s dark syntax palette. The title provides an accessible name without adding a visible header.

Loading code cards…

console.log("Hello, world!");
<div id="my-code" class="code-card" data-code-title="Greeting" data-code-copy="true">
    <pre><code class="language-javascript">console.log("Hello, world!");</code></pre>
</div>

Put escaped source in <pre><code>, or pass a string with the code option. The source is displayed as text and is never executed.

Language variants

Set language or use a language-* class on the authored code element. Load the matching Prism grammar for highlighting; unregistered languages remain readable as plain text.

HTML

<button type="button" class="btn filled">
    Save changes
</button>

CSS

.message {
    color: var(--md-sys-color-on-primary-container);
    background: var(--md-sys-color-primary-container);
    padding: 1rem;
}

JavaScript

import { PasswordInput } from "kmaterialize";

const input = document.querySelector("#password");
const password = PasswordInput.init(input);
password.toggle();

TypeScript

interface Message {
    text: string;
    visible: boolean;
}

const message: Message = { text: "Saved", visible: true };

PHP

<?php

$form = [
    "id" => "contact_form",
    "items" => [
        ["name" => "email", "type" => "email"],
    ],
];

JSON

{
    "title": "Code examples",
    "language": "javascript",
    "copy": true
}

YAML

page:
  title: Code examples
  language: javascript
  copy: true

Shell

npm install kmaterialize prismjs

Python

def greet(name: str) -> str:
    return f"Hello, {name}!"

print(greet("World"))

Handlebars

<section>
    <h2>{{title}}</h2>
    {{#each items}}
        <p>{{this.label}}</p>
    {{/each}}
</section>

With or without copy

Choose copy: true or copy: false, or set data-code-copy in the markup. The copy control uses Crazy Button with keyboard activation. A successful copy changes its icon to a check mark for two seconds; a failed copy shows an error icon. Copy preserves the original source and whitespace, excluding copy feedback.

const copyEnabled = true;
const copyEnabled = false;
<div id="my-code" class="code-card" data-code-title="Greeting" data-code-copy="false">
    <pre><code class="language-javascript">console.log("Hello, world!");</code></pre>
</div>

Clipboard access requires HTTPS or localhost. A failed copy reports “Unable to copy”; the source stays selectable.

Custom code

Edit the source, change its language and title, or toggle the copy button. Use plain text for logs and custom formats that do not need syntax highlighting.

{
    "message": "Your custom code",
    "copy": true
}

Current configuration

CUSTOM FORMAT
name => Example
state => ready

Setup and API

Install kmaterialize and the optional prismjs peer when you use highlighting. CodeCard styles and token colors are included in Materialize CSS.

npm install kmaterialize prismjs
import { CodeCard } from "kmaterialize";
import "kmaterialize/dist/css/materialize.css";

const card = CodeCard.init(document.querySelector("#my-code"), {
    code: "const answer = 42;",
    language: "javascript",
    title: "Example",
    copy: true,
});
await card.ready;

For markup-based initialization, call M.AutoInit() or CodeCard.init(document.querySelectorAll(".code-card")). Add no-autoinit when initializing explicitly alongside AutoInit. Await ready before interacting with highlighted content.

// Prism includes HTML, CSS, and JavaScript by default.
// Register additional grammars before initializing CodeCard.
const scope = window;
if(!scope.Prism) scope.Prism = { manual: true };
const { default: Prism } = await import("prismjs");
Prism.manual = true;
await import("prismjs/components/prism-typescript.js");
await import("prismjs/components/prism-markup-templating.js");
await import("prismjs/components/prism-php.js");
await import("prismjs/components/prism-handlebars.js");

Keep Prism in manual mode so it does not also highlight unrelated code blocks. Register a custom grammar through Prism.languages, or use highlight: false for plain text without a Prism dependency.

OptionTypeDefaultPurpose
codestringAuthored code textSource to display and copy.
languagestringAuthored language or plainPrism language identifier; unregistered grammars display plain text.
titlestringEmptyAccessible name for the code block; no visible header.
copybooleantrueShow or hide the copy button.
highlightbooleantrueUse Prism highlighting. Set false to avoid loading Prism.
copyLabel / copiedLabel / errorLabelstringCopy code / Copied! / Unable to copyAccessible button label and copy feedback.
await card.update({
    code: '{ "saved": true }',
    language: "json", // Load the Prism JSON grammar first.
    title: "Response",
    copy: false,
});
const source = card.getCode();
await card.update({ copy: true });
const copied = await card.copy();
card.destroy();

copy() returns whether the copy succeeded; it returns false when copying is disabled. The bubbling codecopy event exposes detail.success. destroy() removes listeners and restores the authored markup.