onethity/slim4-twig-view

Slim Framework 4 twig view 的分支。

3.0.0-beta 2019-08-20 00:55 UTC

This package is not auto-updated.

Last update: 2024-09-23 20:27:50 UTC


README

这是一个 slim/twig-view 组件,但为了与 Slim 4 兼容而进行了分支。

安装

通过 Composer

$ composer require onethity/slim4-twig-view

需要 Slim Framework 4 和 PHP 7.1.0 或更高版本。

使用方法

// Create Container
$container = new Container();

// Set container to create App with on AppFactory
AppFactory::setContainer($container);
$app = AppFactory::create();

// Register Twig View helper
$container->set('view', function ( ) use ($app) {
    $view = new \Slim\Views\Twig(__DIR__ . '/../tpl/', [
        'cache' => false,
    ]);
    
    // Instantiate and add Slim specific extension
    $uriFactory = new \Slim\Psr7\Factory\UriFactory();
    $uri = $uriFactory->createFromGlobals($_SERVER);
    $routeParser = $app->getRouteCollector()->getRouteParser();
    $basePath = $app->getBasePath();
    $view->addExtension(new \Slim\Views\TwigExtension($routeParser, $uri, $basePath));

    return $view;
});

// Define named route
$app->get('/hello/{name}', function ($request, $response, $args) {
    return $this->get('view')->render($response, 'index.html.twig', [
        'name' => $args['name']
    ]);
})->setName('profile');

// Render from string
$app->get('/hi/{name}', function ($request, $response, $args) {
    $str = $this->get('view')->fetchFromString('<p>Hi, my name is {{ name }}.</p>', [
        'name' => $args['name']
    ]);
    $response->getBody()->write($str);
    return $response;
});

// Run app
$app->run();

自定义模板函数

TwigExtension 为您的 Twig 模板提供以下函数

  • path_for() - 返回给定路由的 URL。
  • base_url() - 返回 Uri 对象的基本 URL。
  • is_current_path() - 如果提供的路由名称和参数对于当前路径有效,则返回 true。
  • current_path() - 渲染当前路径,带或不带查询字符串。

您可以使用 path_for 生成任何名为路由的 Slim 应用程序的完整 URL,并使用 is_current_path 来确定是否需要将链接标记为活动状态,如以下示例 Twig 模板所示

{% extends "layout.html" %}

{% block body %}
<h1>User List</h1>
<ul>
    <li><a href="{{ path_for('profile', { 'name': 'josh' }) }}" {% if is_current_path('profile', { 'name': 'josh' }) %}class="active"{% endif %}>Josh</a></li>
    <li><a href="{{ path_for('profile', { 'name': 'andrew' }) }}">Andrew</a></li>
</ul>
{% endblock %}

致谢

许可

MIT 许可证 (MIT)。请参阅 许可文件 了解更多信息。