Appearance
html 助手
¥html Helper
html Helper 允许你使用名为 html
的标记在 JavaScript 模板字面量中编写 HTML。使用 raw()
,内容将按原样渲染。你必须自己转义这些字符串。
¥The html Helper lets you write HTML in JavaScript template literal with a tag named html
. Using raw()
, the content will be rendered as is. You have to escape these strings by yourself.
导入
¥Import
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
¥Insert snippets into JSX
将内联脚本插入 JSX:
¥Insert the inline script into 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>
)
})
充当功能组件
¥Act as functional component
由于 html
返回 HtmlEscapedString,因此它可以充当功能齐全的组件而无需使用 JSX。
¥Since html
returns an HtmlEscapedString, it can act as a fully functional component without using JSX.
使用 html
代替 memo
来加速进程
¥Use html
to speed up the process instead of memo
typescript
const Footer = () => html`
<footer>
<address>My Address...</address>
</footer>
`
接收 props 并嵌入值
¥Receives props and embeds values
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>`)
})
提示
¥Tips
得益于这些库,Visual Studio Code 和 vim 还将模板字面量解释为 HTML,从而允许应用语法高亮和格式化。
¥Thanks to these libraries, Visual Studio Code and vim also interprets template literals as HTML, allowing syntax highlighting and formatting to be applied.