0

I got a dynamic content in layout which is takes vales from database. What is the best way to achieve this rather than passing values from controller.

Is it possible to call an entity from view? I am using php template.

4

2 回答 2

2

MVC上下文中没有使用控制器来调用模型实体是没有意义的,至少您可以使用 ajax 调用来获取更新的内容,该控制器返回JsonResponse以避免页面刷新

于 2015-04-28T08:08:33.257 回答
1

这可以通过树枝扩展来实现。

注册一个树枝扩展 TWIG EXTENSION

传递给 __constructor() - @doctrine 服务

services.yml

   my.twig.extension:
      class: twig\namespace\path
      arguments:
          kernel: "@kernel"
          doctrine: "@doctrine"
      tags:
        - { name: twig.extension }

Constructor of the new twig extension

protected $kernel;
protected $doctrine;

public function __construct($kernel, $doctrine)
{
  $this->kernel   = $kernel;
  $this->doctrine = $doctrine;
}

写一些方法:

/** @var string $repository. Example: AppBundle:Product' */
public function myEntity($repository)
{
  $manager = $this->doctrine->getManager();
  return $manager->getRepository($repository);
}

在树枝扩展中注册 myEntity 方法:

public function getFunctions()
{
    return array(
        'myEntity' =>  new \Twig_Function_Method($this, 'myEntity'),

    );
}

现在在您的树枝模板中,您可以访问任何存储库:

For example:

{# 
    myEntity('SomeBundle:coolEntity').find()
    myEntity('SomeBundle:coolEntity').findAll()
    myEntity('SomeBundle:coolEntity').findBy()
    ...
#}
{% for item in myEntity('SomeBundle:coolEntity').findAll() %}
  {{ item.getId() }}
{% endfor %}
于 2015-04-28T10:27:22.567 回答