2 回答
TA贡献1895条经验 获得超7个赞
共享相同数据的路由也可以使用相同的响应程序来呈现内容。
伪示例:
<?php
namespace App\Responder;
use Psr\Http\Message\ResponseInterface;
use Slim\Views\Twig;
final class Responder
{
private $twig;
public function __construct(Twig $twig)
{
$this->twig = $twig;
}
public function render(ResponseInterface $response, string $template, array $data = []): ResponseInterface
{
$shared = ['item1', 'item2'];
$data = array_replace(shared, $data);
return $this->twig->render($response, $template, $data);
}
}
用法
$this->responder->render($response, 'index.twig', ['page' => 'content']);
或者...
use App\Responder\Responder;
// ...
$app->get('/index', function($request, $response, $args){
return $this->get(Responder::class)->render($response, 'index.twig', ['pagecontent' => 'This is some content for /index only']);
});
$app->get('/about', function($request, $response, $args){
return $this->get(Responder::class)->render($response, 'about.twig', ['pagecontent' => 'You can have custom content for /about']);
});
$app->get('/contact', function($request, $response, $args){
return $this->get(Responder::class)->render($response, 'contact.twig', ['pagecontent' => '...and /contact as well']);
});
TA贡献2019条经验 获得超9个赞
一种选择是将这些项目作为全局变量添加到 TwigEnvironment,以便它们在每个模板中可用。
首先,您需要将全局变量添加到Twig环境中:
// A simple items provider which helps you generate a list of items
// You can change this to something that reads the items from database, etc.
class ItemsProvider {
public function getItems()
{
return ['item 1', 'item 2', 'item 3', 'item-4', ];
}
}
// Set view in Container
$container->set('view', function($c) {
$twig = Twig::create('<path-to-tiwg-templates'>);
// get items from items-provider and add them as global `items` variable
// to all twig templates
$twig->getEnvironment()->addGlobal('items', $c->get('items-provider')->getItems());
return $twig;
});
// set sample items, you can modifiy this
$container->set('items-provider', function($c){
return new ItemsProvider;
});
现在变量items可用于每个 Twig 模板,而无需将其显式传递给render方法:
布局.树枝:
These are some items available in every twig template:<br>
<ul>
{% for item in items%}
<li>{{ item }}</li>
{% endfor %}
</ul>
<br>
And this is some page specific content:<br>
{% block content %}
{{ pagecontent }}
{% endblock %}
所有三个模板index.twig,about.twig和contact.twig都可以扩展layout.twig:
{% extends 'layout.twig' %}
对于layout.twig中使用的相同变量,每个路由具有不同值的路由定义:
$app->get('/index', function($request, $response, $args){
return $this->get('view')->render($response, 'index.twig', ['pagecontent' => 'This is some content for /index only']);
});
$app->get('/about', function($request, $response, $args){
return $this->get('view')->render($response, 'about.twig', ['pagecontent' => 'You can have custom content for /about']);
});
$app->get('/contact', function($request, $response, $args){
return $this->get('view')->render($response, 'contact.twig', ['pagecontent' => '...and /contact as well']);
});
- 2 回答
- 0 关注
- 91 浏览
添加回答
举报