borschphp/smarty

Borsch Framework 应用的 smarty 模板引擎包装器。

0.1.1 2022-02-19 17:45 UTC

This package is auto-updated.

Last update: 2024-09-20 00:04:10 UTC


README

Build Status Latest Stable Version License

Borsch 的 TemplateRendererInterface 的 Smarty 实现。

此包是 Borsch 框架的一部分。

安装

通过 composer

composer require borschphp/smarty

Borsch 框架集成

打开文件 config/container.php,然后添加您的 TemplateRendererInterface 定义。

use Borsch\Smarty\Smarty;
use Borsch\Template\TemplateRendererInterface;

/*
 * Template renderer definitions
 * -----------------------------
 *
 * Defining the TemplateRendererInterface here so our HomeHandler handler (see upper) can use it when instantiated.
 * The default Borsch Smarty renderer is used.
 * We cache it so that it is not re-created when fetched a second time.
 */
$container->set(TemplateRendererInterface::class, function () {
    $smarty = new Smarty();
    $smarty->setTemplateDir(__DIR__.'/../resources/templates');
    $smarty->setCompileDir(__DIR__.'/../storage/smarty/templates_c');
    $smarty->setCacheDir(__DIR__.'/../storage/smarty/cache');

    return $smarty;
})->cache(true);

要在处理器中加载它,请将其添加为构造函数的参数

class HomeHandler implements RequestHandlerInterface
{

    /** @var TemplateRendererInterface */
    protected $renderer;

    /**
     * HomeHandler constructor.
     * @param TemplateRendererInterface $renderer
     */
    public function __construct(TemplateRendererInterface $renderer)
    {
        $this->renderer = $renderer;
    }

    /**
     * @inheritDoc
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        return new HtmlResponse($this->renderer->render('home'));
    }
}

用法

$smarty = new \Borsch\Smarty\Smarty();

// Adding some directories where templates are located
$smarty->addPath(__DIR__.'/templates');
$smarty->addPath(__DIR__.'/templates/error', 'error');
$smarty->addPath(__DIR__.'/templates/success', 'success');

// Assign some variables
$smarty->assign([
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3'
]);

// Display the template (with or without .tpl extension)
echo $smarty->render('template_file_name');

许可证

该包根据 MIT 许可证授权。有关更多信息,请参阅许可证文件