【发布时间】:2018-09-15 22:09:45
【问题描述】:
在我的项目中,我经常需要在不同的页面上重复使用相同的模板,通常使用不同的过滤器参数。我考虑使用控制器方法和 twig render 函数来执行它。
在我的控制器中:
public function index(Request $request) {
return $this->render("index.html.twig");
}
public function list(Request $request, array $filterArray = []) {
return $this->render("list.html.twig", [
'items' => $this->getFilteredItems($filterArray)
]);
}
public function entry(Request $request, string $alias) {
return $this->render("entry.html.twig"[
'item' => $this->getItemByAlias($alias)
]);
}
在index.html.twig:
{{ render(controller(
'App\\Controller\\SynthesisController::entityList', {},
{ }
)) }}
在list.html.twig:
{% for item in items %}
<div class="">
<a href="">{{item.name}}</a>
</div>
{% endfor %}
因此它允许我在其他页面中重用实体列表及其布局。在entry.html.twig:
<div class="synthesis-participants">
<div class="row">
<div class="col-sm-6 mb-4">
<div class="h5">Reagents:</div>
{{ render(controller(
'App\\Controller\\SubstanceController::entityList', { 'filterArray': {
'participate': { 'synthesis': item.id, 'role': 10 }
} }, { }
)) }}
</div>
<div class="col-sm-6 mb-4">
<div class="h5">Products:</div>
{{ render(controller(
'App\\Controller\\SubstanceController::entityList', { 'filterArray': {
'participate': { 'synthesis': item.id, 'role': 20 }
} }, { }
)) }}
</div>
</div>
<div class="row">
<div class="col-sm-6 mb-4">
<div class="h5">Diluents:</div>
{{ render(controller(
'App\\Controller\\SubstanceController::entityList', { 'filterArray': {
'participate': { 'synthesis': item.id, 'role': 30 }
} }, { }
)) }}
</div>
<div class="col-sm-6 mb-4">
<div class="h5">Catalysts:</div>
{{ render(controller(
'App\\Controller\\SubstanceController::entityList', { 'filterArray': {
'participate': { 'synthesis': item.id, 'role': 40 }
} }, { }
)) }}
</div>
</div>
<p class="mt-2">{{ item.text }}</p>
</div>
是否可以通过更好的方式实现?
【问题讨论】:
-
这是目前最好的方法。您总是必须调用带有参数的方法。如果您不想渲染模板,则可以使用 Twig 过滤器/功能。但是根据您的设置,我认为您目前拥有最好的选择。
-
您仍然可以通过使用循环来减少一些代码,例如
{% for title, role in { 'foo': 10, 'bar': 20, 'foobar': 30, } %}...{% endfor %} -
看看 SonataBlockBundle github.com/sonata-project/SonataBlockBundle