Twig is a powerful templating engine by SensioLabs the creators of Symfony. If you’re a pure backend developer this may not concern you very much but what if you need to get the results of functions from you back end development and render them for the end user of your application?

With Twig you have the ability to render results from the functions you have written without having to actually place them in the view. This gives us not only added performance by having less code that has to be parsed when the view is rendered but also it gives us added security by lessing the exposure of things like database queries to a variety of malicious actions.

So let’s assume that we need to display the username of someone logged into an application. We could easily just insert some php code onto our page to query the database for this but this is insecure and it can cause longer render times for the view. Instead we are going to use Twig’s render capability to get these results from a controller with a function already set up to do that very thing for you.

Let’s quickly go over what the controller might look like. For our purposes let’s keep it very simple. We are building on what we learned in the previous article on how to use raw SQL with Symfony 3. If you are not familiar with this concept click here.

namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\DependencyInjection;
use Symfony\Component\HttpFoundation\Response;
class DemoController extends Controller
	public function getUsernameAction()
		$id = demoID;
		$conn = $this->get(‘database_connection’);
		$sql = “SELECT username FROM users WHERE id = :id”;
		$statement = $conn->prepare($sql);
        		$statement->bindValue('id', $id);
        		$result = $statement->fetchAll();
		$result = $result[0]['username'];
        		return new Response($result);

This is a very basic controller that extends the default controller and returns the username to us from the database but that doesn’t get it into the template where we really need it.

It’s extremely simple to get results from this or any other controller to render in a Twig template using its render functionality.

{{ render(controller(‘AppBundle:DemoController:getUserName’)) }}

That’s all there is to it. You can add as many functions to extend this controller as you need and render their results in the same way!

Stay in the know with
Annevar Media

Stay in the know with

Annevar Media

Subscribe today for weekly tips on keeping your business secure online, and be the first to learn about our special offers.

You have Successfully Subscribed!