4

In my Symfony2 project, I would like to get the HTML of a file and put it in a variable in my controller.

I have a controller function like this:

public function myControllerAction()
{
   $htmlOtherFile = '';

   return $this->render('@MyBundle/myTargetFile.html.twig', ['htmlOtherFile' => $htmlOtherFile]);
}

The html file I would like to import is in my views folder: htmlOtherFile.html.twig

How can I get the HTML of this file into my $htmlOtherFile variable? I have already tried with file_get_contents, but without success.

3 Answers 3

4

all you need to do is call renderView from your controller on the template and put the contents in a variable.

$html = $this->renderView('/path/myTargetFile.html.twig', [/*options in here*/]);

Be sure to call renderView and not render on its own as that will return a Response instance, and not any HTML.

Alternatively, you can call:

$this->render('/path/myTargetFile.html.twig', [/*options in here*/])->getContent();

to return the html from the response.

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

2 Comments

Why don't you edit an Ilya's answer? He answered with that solution first.
because there was more to add, and I dont write peoples answers for them.
2

If it is twig file - you could try this:

$this->renderView('/path/to/template.html.twig', []);

Comments

0

You can call a controller directly from you twig file if you want.

Use the syntax {{ render(controller('MyBundle:functionName')) }}

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.