wonderboymusic / mustache-css-modules
在 Mustache 模板中使用 CSS Modules。
0.2
2019-11-14 09:12 UTC
Requires
- mustache/mustache: ^2.12
- dev-master
- 0.2
- 0.1
- dev-dependabot/npm_and_yarn/example/json5-and-postcss-modules-2.2.3
- dev-dependabot/npm_and_yarn/example/decode-uri-component-0.2.2
- dev-dependabot/npm_and_yarn/example/loader-utils-and-postcss-modules-1.4.1
- dev-dependabot/npm_and_yarn/example/minimatch-and-gulp-3.1.2
- dev-dependabot/npm_and_yarn/example/copy-props-2.0.5
- dev-dependabot/composer/mustache/mustache-2.14.1
- dev-dependabot/npm_and_yarn/example/path-parse-1.0.7
- dev-dependabot/npm_and_yarn/example/hosted-git-info-2.8.9
- dev-dependabot/npm_and_yarn/example/y18n-3.2.2
- dev-dependabot/npm_and_yarn/example/ini-1.3.8
This package is auto-updated.
Last update: 2024-09-05 04:35:24 UTC
README
在 mustache 模板中使用 CSS Modules
example 文件夹包含一个示例实现。
安装
$ composer require wonderboymusic/mustache-css-modules
将此存储库中 js/ 文件夹的内容移动到您项目的根目录,然后
$ npm i
环境
您必须在应用程序的环境中设置 MUSTACHE_CSS_DIR。此值将用于查找 Mustache 模板和位于其旁边的 SCSS 文件。
JavaScript 文件将在项目根目录相对路径下检查此目录
const cssDir = path.join(__dirname, process.env.MUSTACHE_CSS_DIR);
PHP 文件将查找包含您的 Mustache 模板的文件夹的绝对路径
$cssDir = getenv('MUSTACHE_CSS_DIR');
在自动加载之前,您可以直接在引导文件中设置此值
putenv('MUSTACHE_CSS_DIR=' . __DIR__ . '/src/templates'); require_once __DIR__ . '/vendor/autoload.php'; require_once __DIR__ . '/src/app.php';
用法
假设您有一个名为 src/templates 的文件夹中包含一些 Mustache 模板。如果您有一个 footer.mustache 文件,请在同一文件夹中添加一个 footer.scss 文件。
src/templates/footer.mustache
src/templates/footer.scss
在 footer.scss 中声明的样式将限定在 footer.mustache 中,因此您无需担心全局名称冲突。您声明的所有类名都可以用于您的视图逻辑,并且将是唯一的,因此您也无需担心 CSS 冲突或嵌套选择器。
首先,声明您的样式
/* footer.scss */ .wrap { display: block; margin: 0 auto; width: 780px; }
在您的 Mustache 模板中使用 .wrap 的值
<footer class="{{ css.footer.wrap }}">Copyright © 2019</footer>
将 footer 作为 Mustache 文件中的模板使用(例如 home.mustache)
<!doctype html> <html> <head> <title>Mustache + CSS Modules = 🤯</title> </head> <body> <main class="{{ css.main.wrapper }}"> Some body content on a page that has a footer. </main> {{> footer }} </body> </html>
在所有这些真正起作用之前,您的 PHP 视图逻辑需要向模板公开 css
use Wonderboy\Mustache\ModulesLoader; use Wonderboy\Mustache\Template\Utils; class App { use ModulesLoader; public function run() { $css = Utils::getCSSMap(); $html = $this->render('main', [ 'css' => $css ]); // call after rendering to get collected styles // only partials that are part of the render have their styles collected $styles = $this->getCssModules(); // at this point, you can do whatever you want with the output and with the styles // I prefer to insert them directly into the <head>, at the end $output = str_replace( '</head>', $styles . PHP_EOL . '</head>', $html ); // probably unnecessary, but you can reset the CSS Modules // $this->resetCssModules(); // more logic? echo $output; } } $app = new App(); $app->run();
开发
运行 Gulp 以自动生成所有这些工作的构建工件
$ npm run dev