html 助手
html 助手讓您可以使用名為 html
的標籤,在 JavaScript 樣板字串中撰寫 HTML。使用 raw()
,內容將按原樣呈現。您必須自行逸出這些字串。
匯入
ts
import { Hono } from 'hono'
import { html, raw } from 'hono/html'
html
ts
const app = new Hono()
app.get('/:username', (c) => {
const { username } = c.req.param()
return c.html(
html`<!doctype html>
<h1>Hello! ${username}!</h1>`
)
})
將程式碼片段插入 JSX 中
將內嵌腳本插入 JSX 中
tsx
app.get('/', (c) => {
return c.html(
<html>
<head>
<title>Test Site</title>
{html`
<script>
// No need to use dangerouslySetInnerHTML.
// If you write it here, it will not be escaped.
</script>
`}
</head>
<body>Hello!</body>
</html>
)
})
作為函式元件
由於 html
會回傳 HtmlEscapedString,因此它可以在不使用 JSX 的情況下,作為功能完整的元件。
使用 html
來加速流程,而非使用 memo
typescript
const Footer = () => html`
<footer>
<address>My Address...</address>
</footer>
`
接收 props 並嵌入值
typescript
interface SiteData {
title: string
description: string
image: string
children?: any
}
const Layout = (props: SiteData) => html`
<html>
<head>
<meta charset="UTF-8">
<title>${props.title}</title>
<meta name="description" content="${props.description}">
<head prefix="og: http://ogp.me/ns#">
<meta property="og:type" content="article">
<!-- More elements slow down JSX, but not template literals. -->
<meta property="og:title" content="${props.title}">
<meta property="og:image" content="${props.image}">
</head>
<body>
${props.children}
</body>
</html>
`
const Content = (props: { siteData: SiteData; name: string }) => (
<Layout {...props.siteData}>
<h1>Hello {props.name}</h1>
</Layout>
)
app.get('/', (c) => {
const props = {
name: 'World',
siteData: {
title: 'Hello <> World',
description: 'This is a description',
image: 'https://example.com/image.png',
},
}
return c.html(<Content {...props} />)
})
raw()
ts
app.get('/', (c) => {
const name = 'John "Johnny" Smith'
return c.html(html`<p>I'm ${raw(name)}.</p>`)
})
提示
由於有這些函式庫,Visual Studio Code 和 vim 也會將樣板字串解讀為 HTML,允許套用語法醒目提示和格式化。