Reputation:
I want to store my template text in a databse table.
Name | Text | .....
----------------------------------------------------
Title | My very own Blog | ......
Intro | Hello stranger, this is my blog |
Each item is a record and I want to access each item directly in Twig.
Currently my code is:
public function indexAction()
{
$ObjArr=$EntityManager->getRepository('myBundle:tplitems')->findAll();
foreach($ObjArr as $obj) {
$tplitems[$obj-getName()]=$obj;
}
return $this->render('myBundle::index.html.twig',array('tplitems'=>$tplitems,))
}
which lets me write in Twig:
{{ tplitems.title.text }}
Is there a better/cleaner way to do this ?
Upvotes: 0
Views: 600
Reputation: 34107
Create you own repository method instead of using findAll()
, and use doctrine's index by feature. Quoting from the documentation:
The INDEX BY construct is nothing that directly translates into SQL but that affects object and array hydration. After each FROM and JOIN clause you specify by which field this class should be indexed in the result. By default a result is incremented by numerical keys starting with 0. However with INDEX BY you can specify any other column to be the key of your result, it really only makes sense with primary or unique fields though:
SELECT u.id, u.status, upper(u.name) nameUpper FROM User u INDEX BY u.id
JOIN u.phonenumbers p INDEX BY p.phonenumber
Upvotes: 0