繁体   English   中英

从模板将参数传递给Twig扩展?

[英]Passing parameters to Twig extension from template?

我使用 Twig 扩展从数据库中传递全局变量,如下面的代码所示。 但我想让这更动态地通过id参数从数据库中获取数据..

服务

app.twig.database_globals_extension:
 class: Coursat\CoursatBundle\Twig\Extension\DatabaseGlobalsExtension
 arguments: ["@doctrine.orm.entity_manager"]
 tags:
     - { name: twig.extension }

扩大

<?php

namespace Coursat\CoursatBundle\Twig\Extension;

use Doctrine\ORM\EntityManager;

class DatabaseGlobalsExtension extends \Twig_Extension
{

   protected $em;

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

   public function getGlobals()
   {
      return array (
              "myVariable" => $this->em->getRepository('CoursatBundle:test')->find(##I want to pass a var here from the template##),
      );
   }

   public function getName()
   {
      return "CoursatBundle:DatabaseGlobalsExtension";
   }

}

模板

{{ myVariable.name() }}

将其存储在全局变量中是一个非常糟糕的主意,因为对于您的网站的每次调用都会请求您的数据库。

您可以使用函数来检索这些数据:

<?php

namespace Coursat\CoursatBundle\Twig\Extension;

use Doctrine\ORM\EntityManager;

class DatabaseGlobalsExtension extends \Twig_Extension
{

   protected $em;

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

   public function getFunctions()
   {
        return array(
            new \Twig_SimpleFunction('my_test', array($this, 'myTest')),
        );
   }

   public function myTest($id)
   {
      return $this->em->getRepository('CoursatBundle:test')->find($id);
   }

   public function getName()
   {
      return "CoursatBundle:DatabaseGlobalsExtension";
   }

}

然后在您的Twig模板中,使用它来加载您的实体:

{% set twigVar = my_test(42) %}

但是,这仍然是一个不好的做法,您应该在控制器中而不是视图中加载实体。

class DatabaseGlobalsExtension extends \Twig_Extension
{
    ...
    ...
    public function getFunctions() {
        return array(
             'get_db_global', function($key) {
                  $globals = $this->getGlobals();
                  return isset($globals[$key]) ? $globals[$key] : null;
              }
        );
    }
    ...
    ...
}

内树枝:

   The global with key "Foo" is : {{ get_db_global('foo') }}

如果问题是“从模板向 Twig 扩展传递参数?

例如过滤器

//... 
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class SomeFilterExtension extends AbstractExtension
{

  public function getFilters()
  {
    return [
        new TwigFilter('someFilter', [$this, 'someFilter']),
    ];
}

public function someFilter(mixed $baseValue,mixed $mandatoryParam,mixed $optionalParam = null): mixed
{
    // ....
    return $baseValue;
}

}

内部模板:

// ...
{{ blaBlaBlaValue|someFilter(mandatoryParam) }}
// ...

或者

// ...
{{ blaBlaBlaValue|someFilter(mandatoryParam,optionalParam) }}
// ... 

看 -> Twig Extension

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM