Blog

Getting started with Symfony 4: Response and View

February 27, 2019
Symfony Response and Twig

In the previous article, I have already covered what Route and a Controller is, and how to use them inside Symfony.

As I already explained, the Controller is a function we write to handle request that comes into a Symfony and return a response. As a response you can render a template or even turn objects into JSON for an API.

Most of learning Symfony is to learn installing and using powerful tools. Tools are optional, but they can make your “life” easier. For example, if you want to return HTML as a response, one of the tools which deals with templates is called Twig. If you are using  symfony/skeleton , to be able to use twig, you will have to install it with command  composer require twig . (If you are using Symfony standard website-skeleton, you can skip this step).

Next, you can inject Twig with construct function.

Now create variable in your controller to render a template, and return this variable in a Symfony response.

As you can see, we are rendering  base.html.twig  template, which you can find under  templates  directory inside a Symfony application. This is the default directory for all templates.

Now go to the  base.html.twig  template and add a message inside the block body.

For now, ignore the twig syntax, as we are going to cover this in the future as well, but generally we echo ‘message’ inside h1 tag.

There is a better way of using a twig inside your controllers, other than injecting twig. You can extend your BlogController with AbstractController and render a template like this.

If you visit your application now, you can see your template as a response.

Symfony Twig

Twig is only one of the useful tools that are available. In the future, we will cover few others, which can come handy.

 

You Might Also Like

2 Comments

  • Reply Sebastian I. February 28, 2019 at 07:53

    Should I implement my html only inside base.html.twig?

    • Dejan Vujanović
      Reply dejanvujanovic February 28, 2019 at 10:58

      Generally you create new template and extend ‘base.html.twig’. You use ‘base.html.twig’ to setup default values, which you want to have in every template which extend ‘base.html.twig’. You extend templates with {% extends “base.html.twig” %}

    Leave a Reply