HTML 屬性

有時,需要在網站上添加屬性才能啟用特定功能,例如使用 dir 屬性控制應用程式的佈景主題、決定文字方向,或使用 lang 屬性設定頁面語言。一般來說,將這些屬性添加到 HTML 標記是可行的做法,因為它通常是應用程式的容器。

要在 Qwik City 中應用這些屬性,請將它們添加到 src/entry.ssr.tsx 文件中的 containerAttributes

export default function (opts: RenderToStreamOptions) {
  return renderToStream(<Root />, {
    manifest,
    ...opts,
    // Use container attributes to set attributes on the html tag.
    containerAttributes: {
      lang: "en-us",
      ...opts.containerAttributes,
    },
  });
}

此外,opts.serverData 物件和嵌套物件允許您訪問有關請求的信息,包括 請求標頭網址路由參數 等等。利用這些信息,您可以執行以下操作

export default function (opts: RenderToStreamOptions) {
  // With this route structure src/routes/[locale]/post/[id]/index.tsx
  const isRTL = opts.serverData?.qwikcity.params.locale === 'ar';
 
  return renderToStream(<Root />, {
    manifest,
    ...opts,
    containerAttributes: {
      dir: isRTL ? 'rtl' : 'ltr'
      ...opts.containerAttributes,
    },
  });
}

貢獻者

感謝所有讓這份文件變得更好的貢獻者!

  • bab2683
  • hamatoyogi