简体   繁体   中英

Call controller or view (twig file) from self defined twig extension in smyfony2

i've got a problem in symfony2 at the moment and i don't know how i can solve it. Within a self defined new twig extension I want to call a controller or or a view (a twig file).

How is the correct way to realize this? Can you help me? I've read many symfony2 internet pages but i didn't found a good programming approach for me.

For better understanding why i want to do something like this, here is an exmaple what is my idea: I want to source out some html code into an separate view. This new view is embedded in another view by calling the twig extension.

So how can i realize this?

Thanxs for your help.

As you are using Symfony2, you can inject the templating service to your Twig extension and then call the ->render method.

The extension

<?php

namespace YourPackage\YourBundle\Twig\Extension;

use Symfony\Component\Templating\EngineInterface;

class Test_Extension extends \Twig_Extension
{

   protected $templating;

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

   public function getFunctions()
   {
      return array(
              new \Twig_SimpleFunction('my_test', array($this->myTest()), array('is_safe' => array('html')))
      );
   }

   public function myTest()
   {
      // do some stuffs
      $data = $this->templating->render("SomeBundle:Directory:file.html.twig");
      // ...
      return $data;
   }

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

}

services.yml

# src/YourPackage/YourBUndle/Resources/config/services.yml
services:
    test.test_extension:
        class: YourPackage\YourBundle\Twig\Extension\TestExtension
        arguments: ['@templating']
        tags:
            - { name: twig.extension }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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