mustache/silex-provider

为 Silex 提供的 Mustache 服务程序。

v2.0.0 2016-11-03 06:30 UTC

This package is auto-updated.

Last update: 2024-09-20 10:02:14 UTC


README

MustacheServiceProviderMustache 提供与 Silex 应用程序微框架的集成。

安装

mustache/silex-provider 添加到项目的 composer.json

{
    "require": {
        "mustache/silex-provider": "~2.0"
    }
}

然后安装

php composer.phar install

配置

  • mustache.path(可选):包含 Mustache 模板文件的目录路径。

  • mustache.partials_path(可选):包含 Mustache 部分模板文件的目录路径。如果没有指定,则默认为 mustache.path

  • mustache.partials(可选):模板名称到模板内容的关联数组。如果想要在行内定义部分,请使用此选项。

  • mustache.helpers(可选):Mustache 辅助函数的关联数组。有关更多信息,请参阅 Mustache.php 辅助函数文档

  • mustache.options(可选):Mustache 选项的关联数组。有关更多信息,请参阅 Mustache.php 文档

服务

  • mustache.loader(可选):Mustache 模板加载器实例。此加载器将使用您提供的 mustache.path 选项。您也可以用您自己的东西替换此加载器。

  • mustache.partials_loader(可选):用于加载部分的 Mustache 模板加载器。默认情况下,它将从 mustache.partials_pathmustache.partials 配置选项中加载模板。您也可以用您选择的另一个加载器替换部分加载器。

注册

<?php

$app->register(new Mustache\Silex\Provider\MustacheServiceProvider, array(
    'mustache.path' => __DIR__.'/../views',
    'mustache.options' => array(
        'cache' => __DIR__.'/../tmp/cache/mustache',
    ),
));

使用方法

Mustache 提供商提供了一个 mustache 服务

<?php

$app->get('/hello/{name}', function ($name) use($app) {
    return $app['mustache']->render('hello', array(
        'name' => ucfirst($name),
    ));
});

这将渲染您应用程序的 views 目录中的 hello.mustache 文件。

模板加载

默认情况下,Mustache 服务程序配备了 Filesystem 模板加载器。要开始使用,只需设置一个 mustache.path 选项来告诉它模板所在的位置。但是,您也可以用 任何其他 Mustache Loader 替换此加载器。

为了更出色,您应该检查 Inline 模板加载器

<?php

// ...

$app->register(new MustacheServiceProvider, array(
    'mustache.loader' => new Mustache_Loader_InlineLoader(__FILE__, __COMPILER_HALT_OFFSET__)
));

$app->get('/{name}', function($name) use ($app) {
    return $app['mustache']->render('hello', compact('name'));
})
->value('name', 'world');

// ...

__halt_compiler();

@@ hello
Hello, {{ name }}!

特质

Mustache\Silex\Application\MustacheTrait 为您的应用程序添加了一个 render 辅助函数

<?php
use Silex\Application;

class MyApplication extends Application
{
    use \Mustache\Silex\Application\MustacheTrait;
}

$app = new MyApplication;

现在您可以只需调用 render

<?php

return $app->render('hello', array('name' => 'Justin'));

或 BYO 响应

<?php
$response = new Response;
$response->setTtl(10);

return $app->render('hello', array('name' => 'Justin'), $response);

它还提供了一个 renderTemplate 辅助函数,它返回一个渲染的字符串而不是一个 Response 对象。

定制

您可以通过扩展 mustache 服务来在它使用之前对其进行修改

<?php

$app['mustache'] = $app->share($app->extend('mustache', function ($mustache, $app) {
    $mustache->addHelper('app', $app);
    $mustache->setLogger($app['monolog']);

    return $mustache;
}));