垃圾 / smarty-service-provider
Smarty 服务提供者,用于 Silex
Requires
- php: >=7.1.0
- smarty/smarty: ^4.5
Requires (Dev)
- silex/silex: ~2.0
README
SmartyServiceProvider 为 [Smarty] (https://smarty.php.ac.cn) 模板引擎提供集成。
参数
-
smarty.dir (字符串,可选):包含 Smarty 分发的目录路径(包含有 libs 和 demo 文件的目录)。如果未提供,提供者假定 Smarty 类已被加载。
-
smarty.instance (\Smarty,可选):Smarty 类的实例。如果未提供,将由提供者创建。
-
smarty.options (数组,可选):要设置的 smarty 类变量的关联数组。有关更多信息,请参阅 [Smarty 文档] (https://smarty.php.ac.cn/docs/en/api.variables.tpl)。
-
smarty.configure (调用函数,可选):一个接受一个参数的调用函数 - Smarty 类实例。它在提供者的 register() 方法期间被调用。您可以使用此选项进行一些自定义 smarty 配置,例如。
服务
- smarty:The
Smarty
实例。与 Smarty 交互的主要方式。
安装
安装 Smarty 特性的最佳方式是使用 Composer
composer require junker/smarty-service-provider
注册
确保您将 [Smarty] (https://smarty.php.ac.cn) 的副本放置在 vendor/Smarty
目录中
use Junker\Silex\Provider\SmartyServiceProvider; define('SMARTY_PATH', __DIR__ . '/../../../../vendor/Smarty'); $app->register(new SmartyServiceProvider(), array( 'smarty.dir' => SMARTY_PATH, 'smarty.options' => array( 'template_dir' => SMARTY_PATH . '/demo/templates', 'compile_dir' => SMARTY_PATH . '/demo/templates_c', 'config_dir' => SMARTY_PATH . '/demo/configs', 'cache_dir' => SMARTY_PATH . '/demo/cache',),));
注意
Smarty 没有编译到 silex.phar
文件中。您必须将您自己的 [Smarty] (https://smarty.php.ac.cn) 复制到您的应用程序中。
使用
Smarty 提供者提供了一个 smarty
服务
$app->get('/hello/{name}', function ($name) use ($app) { return $app['smarty']->display('hello.tpl', [ 'name' => $name, ]); });
这将渲染一个名为 hello.tpl
的文件,该文件位于您在 smarty.options
中传入的配置模板文件夹中。
在任意的 Smarty 模板中,app
变量指向 Application 对象。因此您可以从您的视图中访问任何服务。例如,要访问 $app['request']->getHost()
,只需在您的模板中放入以下内容
{$app.request->getHost()}
使用相同的 smarty.options 获取新的 smarty 实例
$smarty2 = $app['smarty.new_instance']();
特性
class Application extends \Silex\Application { use \Junker\Silex\Application\SmartyTrait; } $app->render('hello.tpl', [ 'name' => $name, ]);
模板使用
{path _name='app.login'} same as $app['url_generator']->generate('app.login'); {path _name='app.product' id=11} same as $app['url_generator']->generate('app.product', ['id' => 11]); {url _name='app.login'} same as $app['url_generator']->generate('app.login', UrlGeneratorInterface::ABSOLUTE_URL); {trans _name='err.access_forbidden'} same as $app['translator']->trans('err.access_forbidden'); {trans _name='warn.my_city' city='London'} same as $app['translator']->trans('warn.my_city', ['%city%' => 'London']); {trans}hello{/trans} same as $app['translator']->trans('hello'); {transChoice _name='days' _count=5} same as $app['translator']->transChoice('days', 5, ['%count%' => 5]);