awesome9 / templates
WordPress 文件系统和模板的包装器。
1.0.4
2021-07-10 02:26 UTC
Requires
- php: >=5.6
README
📃 关于模板
此包提供了在插件或主题中使用模板的便捷性,同时也提供了类似于 WooCommerce 的模板系统。
该包的灵感来源于 Templates micropackage。
💾 安装
composer require awesome9/templates
🕹 使用
首先,您需要初始化您的存储。
Awesome9\Templates\Storage::get() ->set_basedir( dirname( __FILE__ ) ) ->set_baseurl( plugins_url( __FILE__ ) );
案例 # 1:随机文件夹
假设您的模板树看起来像这样
my-plugin/
├── admin/
│ └── templates/
│ ├── notice.php
│ └── settings.php
└── frontend/
└── templates/
├── profile.php
└── welcome.php
在上面的例子中,我们有两个带有模板的位置,让我们将它们定义为存储。
Awesome9\Templates\Storage::get()->add( 'admin', 'admin/templates' ); Awesome9\Templates\Storage::get()->add( 'frontend', 'frontend/templates' );
然后您可以轻松地渲染模板
$template = new Awesome9\Templates\Template( 'frontend', 'author', [ 'author' => $user_name, 'posts' => get_posts( [ 'author' => $user_id ] ), ] ); $template->render();
模板文件可能看起来像这样
<p>Howdy, <?php $this->the( 'author' ); ?></p> <p>Posts by Author:</p> <ul> <?php foreach ( $this->get( 'posts' ) as $post ) : ?> <li><?php echo $post->post_title; ?></li> <?php endforeach; ?> </ul>
案例 # 2:首先从主题获取模板
假设您的模板树看起来像这样
my-plugin/
├── templates/
│ ├── notice.php
│ └── profile.php
some-theme/
├── my-plugin/
│ ├── notice.php
│ └── settings.php
在这种情况下,我们设置了插件和主题文件夹名进行模板查找。
Awesome9\Templates\Storage::get()->set_for_theme( 'templates', 'my-plugin' );
在模板文件中访问变量
在模板文件中,$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 Awesome9\Templates\Template( $storage_name = 'frontend', $template_name = 'profile', $variables = [ 'var_key' => $var_value, ] );
辅助函数
您也可以使用过程式方法
// Print the template. Awesome9\Templates\template( $storage_name, $template_name, $variables ); // Get the template output. Awesome9\Templates\get_template( $storage_name, $template_name, $variables );
所有参数与 Template
类相同。