Getting Started
Assuming you scaffolded the VitePress project in ./docs, the initial structure should look like this:
.
├─ docs
│ ├─ .vitepress
│ │ └─ config.js
│ ├─ api-examples.md
│ ├─ markdown-examples.md
│ └─ index.md
└─ package.jsonInstallation
Add vitepress-templ-preview and its peer dependency css-tree to your project:
npm add -D vitepress-templ-preview css-treepnpm add -D vitepress-templ-preview css-treeyarn add -D vitepress-templ-preview css-treeVitePress Configuration
- Register the plugin in
.vitepress/config.mts. - Register a rendering component in
.vitepress/theme/index.ts— either a predefined one or a custom component.
// .vitepress/config.mts
import { defineConfig } from "vitepress";
import viteTemplPreviewPlugin from "vitepress-templ-preview";
export default defineConfig({
/* ... */
markdown: {},
vite: {
plugins: [viteTemplPreviewPlugin()],
},
/* ... */
});//.vitepress/theme/index.ts
import type { Theme } from "vitepress";
import DefaultTheme from "vitepress/theme";
import { VTPIconTabs } from "vitepress-templ-preview/components";
import "vitepress-templ-preview/style.css";
export default {
extends: DefaultTheme,
enhanceApp({ app }) {
/* Make sure to name the tag `VTPLivePreview` */
app.component("VTPLivePreview", VTPIconTabs);
},
} satisfies Theme;INFO
See Plugin Options for available configuration.
Search
The plugin provides a sanitizeMarkdownForSearch helper that strips <templ-demo> tags from the markdown source to prevent build errors with VitePress local search.
import { sanitizeMarkdownForSearch } from 'vitepress-templ-preview/sanitizer';
export default defineConfig({
/* ... */
themeConfig: {
search: {
provider: 'local',
options: {
_render(src, env, md) {
sanitizeMarkdownForSearch(src, env, md)
},
},
},
/* ... */
});
/* ... */
});IMPORTANT
sanitizeMarkdownForSearch accepts a fourth parameter for inputDir, if it has been set in the plugin options. See Plugin Options.
Templ Project Setup
Initialize a Go module in the
docsfolder:bashcd docs go mod init components_demo go get github.com/a-h/templCreate a
components/hellofolder with anindex.mdand ahello-demo.templfile:templpackage hello templ HelloDemo() { @hello("World!!!") } templ hello(name string) { <div>Hello, { name }</div> }
Your project structure should now look like this:
.
├── docs
│ ├─ .vitepress
│ │ └─ config.js
│ ├─ api-examples.md
│ ├─ markdown-examples.md
│ ├─ index.md
│ ├─ components
│ │ ├─ hello
│ │ │ ├─ hello-demo.templ
│ │ │ └─ index.md
│ ├─ go.mod
│ ├─ go.sum
└─ package.jsonEmbed in Markdown
Use the templ-demo tag to embed and preview a templ component in your markdown files.
Edit components/hello/index.md:
<templ-demo src="hello-demo" />IMPORTANT
The src attribute is required. Set it to the templ file name without the extension.
For more options, see Rendering Components.
Run the Project
Start the local dev server:
npm run docs:devpnpm run docs:devyarn docs:devVisit the page for the hello component you just created. Your project is now up and running.