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 を使用せずに完全に機能するコンポーネントとして機能します。
memo
の代わりに html
を使用して処理速度を向上させる
typescript
const Footer = () => html`
<footer>
<address>My Address...</address>
</footer>
`
プロップスを受け取り、値を埋め込む
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として解釈し、構文の強調表示とフォーマットを適用できます。