从向数据库发出请求的树枝模板调用函数,然后尝试将其 return 作为数组

Calling a function from twig template where a request is made to the database then trying to return it as an array

我正忙于进行某个测试,我需要使用两个参数(category_id 和 archetype_id)从数据库中调用一个变量。我是 symfony 的新手,我不知道如何从我的控制器函数中 return 一个数组。它要么返回为“{[]}”,要么表示它只能是一个字符串。

我试过使用 JsonResponse,但我不确定为什么我在我的 Twig 模板中收到它作为字符串。

在我的树枝模板中:

{% set variable = render(controller('App\Controller\TestController::getFromDatabase', {'c': 1 , 'a': 12 })) %}
{{ dump variable }}

在我的控制器中:

public function getFromDatabase(int $c, int $a)
    {
        $variables = $this->getDoctrine()->getRepository('App\Entity\Variables')->findBy(['category_id' => $c, 'archetype_id' => $a]);
        return new JsonResponse($variables);
    }

how the data is show, as a string

令人沮丧的是,我知道如何只用 php 和普通编码来做到这一点,但我还不能完全理解 Symfony(似乎比平常有更多的步骤?)

this is what i want to request from my database as an example

谁能告诉我如何在调用时将数组从函数传递到我的 twig 模板?我发现我需要的另一个数组有一个奇怪的解决方法,它看起来像这样,但我认为这不是正确的方法,在这里我只是将字符串放入数组中:

{% set question1 = render(controller('App\Controller\TestController::randomNumberSet', {'amount': (ArchetypeCombi[randomNumbers[q]].c1)|length-1 })) %}
                        {% set question1 = question1|replace({'[': ''}) %}
                        {% set question1 = question1|replace({']': ''}) %}
                        {% set question1 = question1|split(',') %}

我将不胜感激 ;)

绝对不应该从 Twig 渲染控制器方法。
考虑改为创建自定义 Twig Extension

假设 autowire 已启用并且您使用的是默认 services.yaml 配置,以下应该可以正常工作。否则,您可能需要手动将 class 注册为服务,用 twig.extension 标记并将 EntityManager 定义为参数。

// src/Twig/AppExtension.php
namespace App\Twig;

use Doctrine\ORM\EntityManagerInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use App\Entity\Variables;

class AppExtension extends AbstractExtension
{
  private $entityManager;

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

  public function getFunctions()
  {
    return [
      new TwigFunction('getVariables', [$this, 'getVariables'])
    ];
  }

  public function getVariables(int $categoryId, int $archetypeId)
  {
    $parameters = ['category_id' => $categoryId, 'archetype_id' => $archetypeId];
    $repository = $this->entityManager->getRepository(Variables::class);
    return $repository->findBy($parameters);
  }
}

然后在模板中调用自定义 Twig 函数

{% set variables = getVariables(1, 12) %}
{{ dump(variables) }}