使い方
基本的な流れは1回の呼び出しで完結します。コンテンツと任意のCSS設定をTailwindPHPに渡すと、見つかったクラスに対応するCSSが返されます。マークアップからクラス名を抽出し、解決済みのテーマに基づいてコンパイルした結果、実際に使用するユーティリティだけが含まれます。
use TailwindPHP\tw;
$css = tw::generate('<div class="flex items-center p-4 bg-blue-500">Hello</div>');
2つ目の引数を省略すると、generate()は既定の@import "tailwindcss"(テーマ + Preflight + ユーティリティ)を使います。カスタマイズするには、CSS文字列または配列を渡します。
コンテンツのスキャン
TailwindPHPは、コンテンツ内のclass属性とclassName属性を読み取ってクラス名を見つけます。抽出される内容を確認するには、tw::extractCandidates()を使います。
use TailwindPHP\tw;
tw::extractCandidates('<div class="flex p-4" className="bg-blue-500">');
// ['flex', 'p-4', 'bg-blue-500']
class属性とclassName属性の両方がスキャンされ、返されるリスト内の重複は削除されます。[mask-type:luminance]やbg-[#1da1f2]などの任意の候補も同じ方法で抽出され、有効であればコンパイルされます。ここに表示される内容が、generate()でコンパイルされる内容そのものです。
入力形式
すべての静的メソッドは、同じ3種類の入力形式を受け付けます。
| 形式 | シグネチャ | 使用する場面 |
|---|---|---|
| 文字列のみ | tw::generate($content) |
既定のテーマを使い、カスタマイズしない場合。 |
| 文字列 + CSS文字列 | tw::generate($content, $css) |
テーマを手早く調整する場合や、ディレクティブをインラインで指定する場合。 |
| 配列 | tw::generate(['content' => ..., 'css' => ...]) |
minify、importPaths、cacheが必要な場合。 |
use TailwindPHP\tw;
// Format 1: String only
tw::generate('<div class="flex">');
// Format 2: String + CSS string
tw::generate('<div class="flex">', '@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');
// Format 3: Array with content, css, and options
tw::generate([
'content' => '<div class="flex p-4">',
'css' => '@import "tailwindcss";',
'minify' => true,
]);
オプションを受け付けるのは配列形式だけです。cssとminifyに加えて、importPaths(Importsを参照)、cache、cacheTtl(Cachingを参照)を指定できます。
再利用可能なコンパイラー
リクエストループ、テンプレートの一括処理、コンポーネントライブラリなど、同じ設定で複数の断片をコンパイルする場合は、コンパイラーインスタンスを1つ使うと効率的です。tw::compile()はテーマとデザインシステムを一度だけ解決し、その後は再利用します。
use TailwindPHP\tw;
$compiler = tw::compile('@import "tailwindcss"; @theme { --color-brand: #3b82f6; }');
$css = $compiler->generate('<div class="flex p-4 bg-brand">');
$candidates = $compiler->extractCandidates('<div class="flex p-4 bg-brand">');
$minified = $compiler->minify($css);
コンパイラーでは、プロパティの検査(properties()、computedProperties()、value()、computedValue())とテーマへのアクセサー(colors()、breakpoints()、spacing())も利用できます。すべてのメソッドについては、完全なAPIを参照してください。
入力CSSの設定
TailwindPHPの機能の多くは、設定として渡すCSS文字列で利用できます。次の項目を参照してください。
- Theme —
@theme変数と名前空間。 - Directives —
@apply、@utility、@layer、@custom-variant。 - Imports —
@import、仮想モジュール、importPaths、Preflight。 - @source — スキャンするファイルとクラスを制御します。