Skip to content

html 헬퍼

html 헬퍼는 JavaScript 템플릿 리터럴에서 html 태그를 사용해 HTML을 작성할 수 있게 해준다. raw()를 사용하면 내용을 그대로 렌더링한다. 문자열을 직접 이스케이프 처리해야 한다.

Import

ts
import { Hono } from 'hono'
import { html, raw } from 'hono/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>
  )
})

기능적 컴포넌트로 동작하기

htmlHtmlEscapedString을 반환하기 때문에, JSX를 사용하지 않고도 완전한 기능의 컴포넌트로 동작할 수 있다.

memo 대신 html을 사용해 프로세스 속도 높이기

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.