我最近一直在使用自己定制的树枝过滤器。我也一直在寻找提高表现的方法。
我很难区分何时应该在服务中构建函数,然后由控制器使用,或者是否应该将其改为树枝过滤器。我想知道哪个执行得更快,或者是否有任何区别?为了澄清我的问题,我想展示如何用两者填充可变照片。
树枝模板将如下所示。它只会用照片数组制作图像元素。
/content/photos.html.twig
{% for photo in photos %}
<img class="lozad card-img read-more-card-item-img" data-src="{{ photo }}">
{% endfor %}
方法 1:在控制器中传递照片变量。控制器可能会使用名为 PhotoService 的服务并调用 getReadMore 函数,同时将其传递给 twig 模板:
function controllerAction(){
$response = $this->render(
'/content/photos.html.twig',
array(
'photos' => $photoService->getReadMorePhotos($posts),
'loadMoreUrl' => $url,
'limit' => $limit
)
}
方法2:改用自定义树枝过滤器:
public function getFilters()
{
return array (new \Twig\TwigFilter('readMorePhotos', array($this, 'getReadMorePhotos')));
}
//Twig filter
public function getReadMorePhotos($posts)
{
...
$photos = [];
foreach ($posts as $post) {
$image = $this->getAbsoluteThumbsPath($post->getImage());
if ($image != null && $image != "" && strpos($image, '/img/posts/default-post.png') === false) {
$gallery[] = $image;
}
}
...
return $photos;
}
在 twig 模板中,photos 变量将像这样填充:
{{set photos = posts|readMorePhotos}}
两种方法有什么区别吗?