在模板中使用doctrine数据库对象 [英] Using doctrine database object in a template

查看:117
本文介绍了在模板中使用doctrine数据库对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Symfony的新手,终于开始了解如何使用Doctrine查询数据库。但是,我很遗憾,如何在Twig模板中使用数据库对象内容。

I am new to Symfony and am finally beginning to understand how to query a database using a Doctrine. However, I am lost as far understanding how to use the database object content in a Twig template.

让我的数据库对象包含产品编号,名称,价格,50不同的产品。完成查询控制器中的数据库后,我执行以下操作,将数据库对象传递到Twig模板中:

Lets say my database object contains product Id's, names, prices, for 50 different products. After I am done querying the database in the controller, I do the following, to pass the database object into the Twig template:

public function searchAction($word)
{
      //query database using the $word slug and prepare database object accordingly

      $dataObject; // contains query results
      return $this->render('GreatBundle:Default:search.html.twig', array('word' => $word));
}

这是我被卡住的地方。现在我有一个Twig模板,我想从控制器传递DB对象,然后打印出我的Twig模板中的数据库数据。

This is where I am stuck. Now I have a Twig template, I would like to pass the DB object from the controller and then print out the database data in my Twig template.

我感谢任何建议

推荐答案

p>我会回答一个例子(我更容易解释)

I'll respond with an example (more easier for me to explain)

你想用slug(你的例子中的var $字)搜索一些东西。假设你想找到一篇文章。

You want to search something with a slug (the var $word in your example). Let's say you want to find a article with that.

所以你的控制器:

public function searchAction($word)
{
   //query database using the $word slug and prepare database object accordingly
   // Search the list of articles with the slug "$word" in your model
   $articleRepository = $this->getDoctrine()->getRepositoy('GreatBundle:Article');
   $dataObject = $articleRepository->findBySlug($word);
   // So the result is in $dataObject and to print the result in your twig, your pass the var in your template
   return $this->render('GreatBundle:Default:search.html.twig', array('result' => $dataObject));
}

树枝模板'GreatBundle:Default:search.html.twig'

The twig template 'GreatBundle:Default:search.html.twig'

{% for item in result %}
{{ item.title }} : {{ item.content }}
{% endfor %}

这篇关于在模板中使用doctrine数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆