Using Twind with Deno

Twind is a tailwind-in-js solution for using Tailwind. Twind is particularly useful in Deno’s server context, where Tailwind and CSS can be easily server side rendered, generating dynamic, performant and efficient CSS while having the usability of styling with Tailwind.

Basic example

In the following example, we will use twind to server side render an HTML page and log it to the console. It demonstrates using the tw function to specify grouped tailwind classes and have it rendered using only the styles specified in the document and no client side JavaScript to accomplish the tailwind-in-js:

  1. import { setup, tw } from "https://esm.sh/twind@0.16.16";
  2. import { getStyleTag, virtualSheet } from "https://esm.sh/twind@0.16.16/sheets";
  3. const sheet = virtualSheet();
  4. setup({
  5. theme: {
  6. fontFamily: {
  7. sans: ["Helvetica", "sans-serif"],
  8. serif: ["Times", "serif"],
  9. },
  10. },
  11. sheet,
  12. });
  13. function renderBody() {
  14. return `
  15. <h1 class="${tw`text(3xl blue-500)`}">Hello from Deno</h1>
  16. <form>
  17. <input name="user">
  18. <button class="${tw`text(2xl red-500)`}">
  19. Submit
  20. </button>
  21. </form>
  22. `;
  23. }
  24. function ssr() {
  25. sheet.reset();
  26. const body = renderBody();
  27. const styleTag = getStyleTag(sheet);
  28. return `<!DOCTYPE html>
  29. <html lang="en">
  30. <head>
  31. <title>Hello from Deno</title>
  32. ${styleTag}
  33. </head>
  34. <body>
  35. ${body}
  36. </body>
  37. </html>`;
  38. }
  39. console.log(ssr());