2

I'm trying to send a variable to a twig file which is not in the typical location, Usually I'm loading views by specifying their path through the Bundle but the file I want to send a variable to is not, hierarchically, on the same level as the other twig templates.

I've a controller which looks like the following:

public function fooAction(Request $request)
{

   *//Query*

    return $this->render('Bundle:file.html.twig', array('varToSend' => $queryResult));
}

I'm pretty sure the Bundle:file.html.twig is wrong but I don't know how else to specify the relevant path in twig.

1
  • 2
    What is the path to file.html.twig? What is the path to Bundle? Commented May 5, 2015 at 12:49

2 Answers 2

3

Twig you would get from container would not work with arbitrary paths, but you can initialize your own twig:

$twig = new \Twig_Environment(new \Twig_Loader_String());
$rendered = $twig->render(
  file_get_contents('/path/to/your/file.html.twig'),
  array('varToSend' => $queryResult)
);

If you need this in more than one place, consider making it a Symfony service in order to not initialize Twig Environment every time.

Note that renderer in this case won't have any of Symfony's Twig Extensions, you'll have to add them manually.

If possible, try to avoid this, and put templates into app/Resources/views or src/AppBundle/Resources/views directories.

Sign up to request clarification or add additional context in comments.

3 Comments

Why do you need to declare $twig?
@A.L Because twig you would get from the container does not work with arbitrary paths. Symfony does not pass \Twig_Loader_String() to it, so it would expect a template to be in specific locations.
I suggest you to add this comment to your question, using \Twig_Environment(... is not a common way.
2

You have to use a path like that :

return $this->render('Bundle:Something:file.html.twig', array(
    'varToSend' => $queryResult
));

And put your file in this folder :

src/Bundle/Resources/views/Something/file.html.twig

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.