bechwebbkonsult/wordpress-template-models

0.0.1 2018-09-24 12:58 UTC

This package is not auto-updated.

Last update: 2024-10-02 21:27:12 UTC


README

模板模型是类方法,在WordPress包含预定的模板文件之前立即执行。如果您有希望在每次渲染模板时都与之绑定的数据,模板模型可以帮助您将逻辑组织到单个位置。

用法

模板模型是一个类,您可以在其中放置一些复杂逻辑。您可以通过扩展提供的 Bechwebb\TemplateModels\TemplateModel 来创建模板模型。

class HomeTemplateModel extends TemplateModel
{
    public $terms = [];

    public function __construct()
    {
        foreach (get_terms(['taxonomy' => 'bf_calendar', 'hide_empty' => false]) as $term) {
            $term->url = get_term_link($term->term_id);
            $this->terms[] = $term;
        }
    }
}

所有模板模型都需要注册到所需的WordPress模板。

use Bechwebb\TemplateModels\TemplateModelProvider;

$templateModelProvider = new TemplateModelProvider;
$templateModelProvider->register('/home.php', \App\TemplateModels\HomeTemplateModel::class);

在模板中,现在所有来自模板模型的可公开访问的属性都可用。

<?php foreach ($terms as $term) : ?>
    <div class="row <?= $term->active ?>">
        <div class="col">
            <a href="<?= $term->url ?>"><?= $term->name ?></a>
        </div>
    </div>
<?php endforeach; ?>

手动使用模板模型

您还可以从任何模板手动加载模板模型并使用参数

use Bechwebb\TemplateModels\TemplateModel;

class CalendarSidebarTemplateModel extends TemplateModel
{
    public $title = '';
    public $posts = [];

    public function __construct($title, $post_type)
    {
        $this->title = $title;

        foreach (get_posts((['post_type' => '$post_type']) as $post) {
            $post->url = get_post_permalink($post->ID);

            $this->posts[] = post;
        }
    }
}

注册模板模型

$templateModelProvider->register('/theme-templates/calendar-sidebar.php', \App\TemplateModels\CalendarSidebarTemplateModel::class);

使用 get_model_template() 来包含模板

get_model_template('/theme-templates/calendar-sidebar.php', 'Sidebar title', 'bf_calendar');