我使用Twig作为我的项目,我想扩展全局对象app.user而不在我的UserClass中添加属性。我的意思是:
我有UserClass:
<?php
namespace Test\CoreBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
* @ORM\Entity(repositoryClass="Test\CoreBundle\Repositories\UserRepository")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
我有知识库:
<?php
namespace Test\CoreBundle\Repositories;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function getCountPosts () {
//some code
return 10;
}
}
如何在Twig模板中访问UserRepository的方法getCountPosts?
答案 0 :(得分:0)
你不能因为业务逻辑必须在控制器中。您可以在实体中创建额外的方法,并在Twig模板中调用它们。
<?php
namespace Test\CoreBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="fos_user")
* @ORM\Entity(repositoryClass="Test\CoreBundle\Repositories\UserRepository")
*/
class User extends BaseUser
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
public function getCountPosts () {
//some code
return 10;
}
}
在你的Twig文件中
{{ app.user.getCountPosts() }}