0

テンプレート TWIG 内で PHP 関数を呼び出す必要があります。その関数を挿入する方法と場所は? ここに私の例: 私のコントローラーは:

namespace BackendBundle\Controller;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use BackendBundle\Entity\Comisiones;
use BackendBundle\Entity\Liquidaciones;
use BackendBundle\Form\ComisionesType;
use BackendBundle\Form\LiquidacionesType;

    /**

* Comisiones controller.
 *
 */
class ComisionesController extends Controller
{
    /**
     * Lists all Comisiones entities.
     *
     */
    public function indexAction()
    {
       $twig = new Twig_Environment($loader);
        $function = new Twig_SimpleFunction("decir_hola", function () {
         $saludo='Hola!';
         return $saludo;
        }); 
        $em = $this->getDoctrine()->getManager();

    $comisiones = $em->getRepository('BackendBundle:Comisiones')->findComisio();

    return $this->render('comisiones/index.html.twig', array(
        'comisiones' => $comisiones,
    ));
}

私のTwigテンプレートは次のとおりです。

{% block body %}
{{decir_hola()}}

{% endblock %}

しかし、次のエラー メッセージが表示されます。

名前空間「BackendBundle\Controller」からクラス「Twig_Environment」をロードしようとしました。別の名前空間の「use」ステートメントを忘れましたか?

何が欠けている?

4

1 に答える 1

3

You need to prefix the class names from Twig with a backslash (e.g. \Twig_Environment instead of Twig_Environment). Otherwise, PHP will treat those class names as if they were part of the current namespace.

However, you shouldn't register your custom Twig functions, filters and so on inside your controller, but register a custom Twig extension instead. You can read more about this in the Symfony documentation.

于 2016-05-13T14:45:18.677 に答える