从 Symfony2 中的树枝模板中获取数据? [英] Fetch data from inside a twig template in Symfony2?

查看:31
本文介绍了从 Symfony2 中的树枝模板中获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数据库中获取数据并将其显示在模板中.我通常会从控制器内部执行此操作并将该数据作为变量传递,但是我想根据调用该方法的模板使用相同的方法获取不同数量的数据.我看过嵌入控制器,但我只想要数据,而不是呈现 HTML http://symfony.com/doc/2.0/book/templating.html#embedding-controllers

I want to fetch data from a database and display it in a template. I would normally do this from within the controller and pass that data as a variable, however I want to fetch different amounts of data using the same method depending on which template is calling that method. I have looked at embedding controllers but I only want the data, not rendered HTML http://symfony.com/doc/2.0/book/templating.html#embedding-controllers

示例

{# views/template1.html.twig #}

{% for item in FetchDBdata('someParam', 20)  %}
    {{ item.name }}
    {{ item.title }}
{% endfor %}


{# views/template2.html.twig #}

{% for item in FetchDBdata('someOtherParam', 40)  %}
    {{ item.name }}
    {{ item.title }}
{% endfor %}

其中 FetchDBdata('someParam', 40) 将在应用程序的服务类中

where FetchDBdata('someParam', 40) would be in a service class in the app

推荐答案

添加到我上面的评论中:

To add to my comment above:

您将有一个控制器,用于获取数据:

You'd have a controller with an action to fetch your data:

Acme\SomeBundle\Controller\DataController.php

/**
 * @Template
 */
public function fetchDataAction($someParam, $quantity) {
    $data = doSomethingWithDatabase();

    return array('data' => $data);
}

Acme\SomeBundle\Resources\view\Data\fetchData.html.twig

{% for item in data %}
    {{ item.name }}
    {{ item.title }}
{% endfor %}

然后在您的 template1template2 中,如果合适,您可以对您的值进行硬编码,或者使用分别传递给这些模板的值.

then in your template1 and template2 you can hardcode your values if that suits, or use values that are passed to those templates respectively.

{% render 'AcmeSomeBundle:Data:fetchData' with {'someParam': 'something', 'quantity': 20} %}

这篇关于从 Symfony2 中的树枝模板中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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