跳转到正文

用法

核心流程只需调用一次:向 TailwindPHP 提供内容和可选的 CSS 配置,它便会返回找到的类对应的 CSS。类名会从标记中提取,并依据解析出的主题进行编译;结果只包含你实际使用的工具类。

PHP
use TailwindPHP\tw;

$css = tw::generate('<div class="flex items-center p-4 bg-blue-500">Hello</div>');

如果不提供第二个参数,generate() 会使用默认的 @import "tailwindcss"(主题 + Preflight + 工具类)。传入 CSS 字符串或数组即可自定义。

内容扫描

TailwindPHP 会读取内容中的 class 和 className 属性来查找类名。若要检查提取到的内容,请使用 tw::extractCandidates():

PHP
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() 将要编译的内容。

输入格式

每个静态方法都接受以下三种相同的输入形式:

格式 签名 使用场景
仅字符串 tw::generate($content) 使用默认主题,不进行自定义。
字符串 + CSS 字符串 tw::generate($content, $css) 快速调整主题或内联指令。
数组 tw::generate(['content' => ..., 'css' => ...]) 需要 minify、importPaths 或 cache 时。
PHP
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(见 导入)、cache 和 cacheTtl(见 缓存)。

可复用编译器

对于同一配置编译多个片段(例如请求循环、一批模板或组件库),使用单个编译器实例的开销更低。tw::compile() 会解析一次主题和设计系统,然后重复使用:

PHP
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())。完整的 APIAPI参考列出了所有方法。

配置输入 CSS

TailwindPHP 的大部分功能都来自你作为配置传入的 CSS 字符串。接下来可阅读:

  • 主题 — @theme 变量和命名空间。
  • 指令 — @apply、@utility、@layer、@custom-variant。
  • 导入 — @import、虚拟模块、importPaths 和 Preflight。
  • @source — 控制要扫描哪些文件和类名。