Skip to content

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>
            // 无需使用 dangerouslySetInnerHTML。
            // 写在这里的内容不会被转义。
          </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">
  <!-- 更多元素会拖慢 JSX,但对模板字面量没有影响。 -->
  <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 &quot;Johnny&quot; Smith'
  return c.html(html`<p>I'm ${raw(name)}.</p>`)
})

小贴士

借助以下工具,Visual Studio Code 与 vim 等编辑器可以把模板字面量识别为 HTML,从而启用语法高亮与格式化。

Released under the MIT License.