micropackage / templates
简单易用的PHP模板引擎
1.1.6
2021-11-15 21:12 UTC
Requires
- php: >=5.6
- micropackage/filesystem: ^1.0
Requires (Dev)
This package is auto-updated.
Last update: 2024-09-16 03:49:04 UTC
README
🧬 关于模板
Templates micropackage是一个非常简单的WordPress模板引擎,支持多种存储。模板不会被解析或缓存,如Blade或Twig模板。它只是一个支持变量的旧式文件加载器。
💾 安装
composer require micropackage/templates
🕹 使用
假设你的模板树结构如下
my-plugin/
├── admin/
│ └── templates/
│ ├── notice.php
│ └── settings.php
└── frontend/
└── templates/
├── profile.php
└── welcome.php
首先,你需要定义至少一个模板存储。在上面的例子中,我们有两个模板存放位置。
Micropackage\Templates\Storage::add( 'admin', $plugin_dir . '/admin/templates' ); Micropackage\Templates\Storage::add( 'frontend', $plugin_dir . '/frontend/templates' );
然后你可以轻松地渲染模板
$template = new Micropackage\Templates\Template( 'frontend', 'profile', [ 'user_name' => $user_name, 'posts' => get_posts( [ 'author' => $user_id ] ), ] ); $template->render();
模板文件可能看起来像这样
<p>Howdy, <?php $this->the( 'user_name' ); ?></p> <p>See your posts:</p> <ul> <?php foreach ( $this->get( 'posts' ) as $post ) : ?> <li><?php echo $post->post_title; ?></li> <?php endforeach; ?> </ul>
在模板文件中访问变量
在模板文件中,$this
指向模板实例,这意味着你可以访问所有模板方法。
基本用法是
$this->the( 'var_name' ); // Prints the value. $var_name = $this->get( 'var_name' ); // Gets the value.
但你也可以使用简写闭包方法
$the( 'var_name' ); // Prints the value. $var_name = $get( 'var_name' ); // Gets the value.
默认变量值
当变量未定义时,你可以指定其默认值
$the( 'var_name', 'Default val' ); $var_name = $get( 'var_name', 'Default val' );
可用的模板方法
模板类方法。
模板构造器参数
$template = new Micropackage\Templates\Template( $storage_name = 'frontend', $template_name = 'profile', $variables = [ 'var_key' => $var_value, ] );
辅助函数
你也可以使用过程式方法
// Print the template. Micropackage\Templates\template( $storage_name, $template_name, $variables ); // Get the template output. Micropackage\Templates\get_template( $storage_name, $template_name, $variables );
所有参数与Template
类相同。
📦 关于Micropackage项目
Micropackages——正如其名所示——是带有少量可重用代码的微包,特别有助于WordPress开发。
目标是拥有多个包,可以通过定义结构来组合在一起创建更大的东西。
Micropackages由BracketSpace维护。
📖 更新日志
📃 许可证
GNU通用公共许可证(GPL)v3.0。有关更多信息,请参阅LICENSE文件。