0

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 ?

6
  • Better or cleaner in which context? Commented Sep 15, 2013 at 18:25
  • Is there a Twig-Function to do this? Or at least a PHP-function? I am not sure if its good practice to have a foreach construct in the controller. Commented Sep 15, 2013 at 18:34
  • That is propably because you have no model, but just a database, and need to transform it's output into the template. Commented Sep 15, 2013 at 18:37
  • No models in symfony2... I use Doctrine, which uses very simple Entities (basically just a class with setters and getters for every variable (=database-field). Commented Sep 15, 2013 at 18:52
  • In Twig I can access the name-property of my entity very simply even without the foreach-construct: {{basics.0.name}} which would in my case result in 'Title'; and {{basics.0.Text}} resulting in 'My very own Blog'. I am interested how others do this and if there for chances is a twig filter that would be better practice to use. Commented Sep 15, 2013 at 18:58

1 Answer 1

0

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.