从 Symfony2 中的树枝模板内部获取数据?

发布于 2024-12-21 06:51:46 字数 671 浏览 2 评论 0原文

我想从数据库中获取数据并将其显示在模板中。我通常会在控制器内执行此操作并将该数据作为变量传递,但是我想使用相同的方法获取不同数量的数据,具体取决于哪个模板调用该方法。我看过嵌入控制器,但我只想要数据,而不是渲染 HTML http ://symfony.com/doc/2.0/book/templatating.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) 为在应用程序的服务类中

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

Example

{# 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 %}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

十年不长 2024-12-28 06:51:46

添加到我上面的评论:

您将有一个带有获取数据的操作的控制器:

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 中,如果合适的话,您可以对您的值进行硬编码,或者使用分别传递给这些模板的值。

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

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 %}

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} %}
假情假意假温柔 2024-12-28 06:51:46

如果您确实确定要从模板更直接地调用模型,我可以看到两个选项:

要么将您需要的服务提供给模板,例如:

public function viewPostsAction() {
    return array('templatingDataService' => $this->get('templating_data_service'));
}

我认为您可以在其中调用方法视图:

{% set someData = templatingDataService.someMethod('params', 40) %}

或者,如果您不想将服务传递给模板以获取所需的数据,那么您可以创建一个 twig 扩展,您可以阅读以下内容: 此处此处此处。 (请注意最后一个链接,尽管我认为它包含很多不必要的步骤,因此我将提供一个较短的版本。

要创建 Twig 函数,例如 FetchDbData:

首先,您需要一个能够执行提升操作的类:

Acme\SomeBundle\Extension\TemplateDataExtension.php

class CurrencyExtension extends \Twig_Extension {
    // Read about \Twig_Extension in my second link.

    private $doctrine;

    public function __construct($doctrine) {
        $this->doctrine = $doctrine;
    }

    public function getName() {
        return 'AcmeTemplateDataExtension';
    }

    public function getFunctions() {
        return array('FetchDbData' => new \Twig_Function_Method($this, 'fetchDbData'));
    }

    public function fetchDbData($someParam, $quantity) {
        // Do whatever you want and return it.
    }
}

您应该能够使用 FetchDbData($params, $quantity) 直接从模板调用它

。将其注册为通过 services.yml 执行的扩展:

parameters:
  template_data_extension.class: Acme\SomeBundle\Extension\TemplateDataExtension

services:
  template_data_extension:
      class:  %template_data_extension.class%
      arguments: [@doctrine]
      tags:
          -  { name: twig.extension }

本质上,这些步骤应该允许您从 twig 访问一个函数(假设我一切正常;))。您可以在一个类中的扩展中添加任意数量的函数,以防止每次需要在视图上访问更多数据时都必须进行多个扩展 - 我不太确定我会选择哪一个,twig 扩展或将服务传递给视图。

希望这将为您提供更多选择,这些选择可能适合您设想的模板系统设计方式:)。

编辑:另外只是一个注释,我想在事物的方案中,辅助对象(用于访问服务或传递服务的树枝扩展)似乎并不坏,因为实际上视图正在与控制器对话以获取一些数据据我所知。另外,我认为可能有一种方法可以访问通过_controller呈现模板自身的控制器,这可能是放置方法的另一个地方。

If you are really certain that you want to call the model more directly from your template you have two options that I can see:

Either you make the service you need available to the template such as:

public function viewPostsAction() {
    return array('templatingDataService' => $this->get('templating_data_service'));
}

which I think you could then call methods on in the view:

{% set someData = templatingDataService.someMethod('params', 40) %}

Alternatively if you don't want to pass the service to the template for it to get the data it requires then you can make a twig extension which you can read about: here, here and here. (Watch out for that last link though I think it includes alot of unnecessary steps so I'll provide a shorter version.

To make a Twig Function such as FetchDbData:

First you need a class that does the lifting:

Acme\SomeBundle\Extension\TemplateDataExtension.php

class CurrencyExtension extends \Twig_Extension {
    // Read about \Twig_Extension in my second link.

    private $doctrine;

    public function __construct($doctrine) {
        $this->doctrine = $doctrine;
    }

    public function getName() {
        return 'AcmeTemplateDataExtension';
    }

    public function getFunctions() {
        return array('FetchDbData' => new \Twig_Function_Method($this, 'fetchDbData'));
    }

    public function fetchDbData($someParam, $quantity) {
        // Do whatever you want and return it.
    }
}

You should be able to call this straight from a template with FetchDbData($params, $quantity).

Now you also need to register this as an extension which you do through services.yml:

parameters:
  template_data_extension.class: Acme\SomeBundle\Extension\TemplateDataExtension

services:
  template_data_extension:
      class:  %template_data_extension.class%
      arguments: [@doctrine]
      tags:
          -  { name: twig.extension }

Essentially those steps should have allowed you to make a function accessible from twig (Assuming I got it all right ;)). You could add as many functions as you want to the extension in one class to prevent having to make multiple extensions every time you need some more data accessible on the view - I'm not really sure which I'd go for though, twig extension or passing a service to the view.

Hopefully this will give you some more options that might fit into how you envisage the design of your templating system :).

Edit: Also just a note to say I suppose in the scheme of things a helper object (twig extension to access a service or passing a service) doesn't seem to bad since really the view is talking back to a controller to get some data as far as I can tell. Also I think there may be a way to access the controller that rendered the template its self through _controller which might be another place to put methods.

许你一世情深 2024-12-28 06:51:46

一个可能的解决方案是使用树枝全局变量。

例如,如果您使用 Doctrine2 并且您的获取数据的方法 findSth 是在存储库 Your\Model 中实现的,您可以定义

#config.yml
twig:
    globals:
        em: @doctrine.orm.entity_manager

{% set data = em.getRepository("Your\Model").findSth(..params...) %}

A possible solution is using twig global variables.

As an example, if you use Doctrine2 and your method to fetch data findSth is implemented in the repository Your\Model, you could define:

#config.yml
twig:
    globals:
        em: @doctrine.orm.entity_manager

And in your template

{% set data = em.getRepository("Your\Model").findSth(..params...) %}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文