跳转到正文

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 &quot;Johnny&quot; Smith'
  return c.html(html`<p>I'm ${raw(name)}.</p>`)
})

提示 ​

借助以下库,Visual Studio Code 和 vim 也能将模板字面量识别为 HTML,从而应用语法高亮和格式化。

基于 MIT 许可证发布。