How to Create a Page in Symfony 6 (Frontend)?

Coding (Symfony)


Introduction to Twig template engine and Symfony Webpack Encore
 
/img/blog/how-to-create-a-page-in-symfony-with-twig-ancore.jpeg

When I was a junior developer I came to a realization pretty quickly.

Despite the value coming from tutorials and documentation one of the best ways to learn a new skill is by doing.

Malcolm Gladwell author of Outliers wrote that to become an expert, we need around 10000 hours of practice. 

Practice does not mean watching videos of how to do things.

Practice means practice!

I am currently learning about a PHP framework called Symfony 6.

My practice will be rewriting my website in it.

Today you’ll learn how I am practicing Symfony by creating front-end web pages in Twig.

 

What is Symfony?

Symfony is a PHP framework.

If you don’t know PHP or need to brush up on the basics here is the post for you

Learn the basics of PHP.

A framework provides built-in components.

They can be authorization or log-in features, or ways to manage security or frontend assets.

Frameworks are useful as they allow you to focus on the things that are special for your website.

So you don’t need to waste your time doing things you don't want.

Symfony is a popular example of these frameworks.

It is made for PHP developers and it includes hundreds of components that you can pull into your project and use.

You can read how to install Symfony here.

The goal of this article is to teach you how to create an HTML page in Symfony.

So you can practice it afterward.

 

Photo by Tran Mau Tri Tam ✪ on Unsplash

 

 

Render the web page from a controller

Symfony is an MVC framework.

I have already explained in detail how MVC work.

The basic is that your project is divided into 3 parts.

Model, View, and Controller.

Controllers ‘control’ requests and responses through the website.

Views are the pages that are shown to the visitors.

Here is a snippet of a basic controller:

 

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class GreetingsController
{
    public function getHello(): Response
    {
        return new Response(
            '< html>< body>< p>Hello< /p>< /body>< /html>'
        );
    }
}

The getHello() is a method in this controller that returns an HTML response that shows the string ‘Hello’.

Despite this working perfectly you can understand how this way of creating a page is not really scalable.

And cumbersome I dare write.

For this reason, Symfony 6 provides a component.

It is called Twig.

 

 

 

 

Basics of Twig

Many frameworks come with their own template engine to show HTML.

Symfony has Twig.

Twig is a light and easy-to-use engine.

It is also as easy to install.

To do so you need to type one command on your terminal.

composer require twig 

In case you don’t know what composer is or how to use it here is an article about the basics of Composer.

Once installed you can swap the return statement into the following one …

return $this->render('hello.html.twig']);

… and create a hello.html.twig file in which you’ll write your HTML page.

 

Using Twig Templates

The secret to being able to scale any project is to have a few stand-alone components that are reusable.

For this reason, is preferable to have HTML in its View file rather than inside a controller.

Symfony has the concept of templates.

They are like HTML pages but with superpowers

Think of that as super Sayan for HTML

 

Photo by Carson Masterson on Unsplash

 

Here is an example of the official documentation

 


< html>
    < head>
        < title>Welcome to Symfony!
    < /head>
    < body>
        < h1>{{ page_title }}

        {% if user.isLoggedIn %}
            Hello {{ user.name }}!
        {% endif %}

        {# ... #}
    < /body>
< /html>

What seems a normal Html page has an if statement embedded in it.

There are dozens of other features available.

Such as variables:

 

< p>{{ user.name }} added this comment on {{ comment.publishedAt|date }}

 

And loops:

{% for user in users %}
    < h1>{{ user.name }}
    < p>{{ user.telephone }}
{% end for %}

 

 

CSS and JavaScript

Twig is not about HTML.

You can get manage images, CSS, and even scripts with it.

To do so you need another component called symfony/asset

 

composer require symfony/asset

 

Once this package has been installed successfully you can use it on the page to load whatever asset you need.

 

< img src="{{ asset('images/logo.png') }}" alt="Symfony!"/>

< link href="{{ asset('css/main.css') }}" rel="stylesheet"/>

< script src="{{ asset('bundles/script/js/loader.js') }}">

Even though this will work fine most modern apps can be developed using CSS framework and Single Page Applications via JS framework.

Symfony makes it easy to use them too via another package called Webpack Encore

 

Photo by Maik Jonietz on Unsplash

 

 

Symfony’s Webpack Encore

Webpack Encore is how Symfony integrates CSS and Javascript into our web pages.

It is easy to install and after that, we can use Sass, Less, ReactJs, VueJs, or whatever we prefer to pull into our project.

This is another component so to install it we need to require it from the composer.

 

composer require symfony/webpack-encore-bundle

 

Then install it via yarn or npm (with the commands yarn install or npm install).

Even though I am fine using the Twig template for my website and I’ll refactor it to ReactJS in the future I do want to use SASS from the start.

To do it I will enable it from the webpack.config.js file.

Then when I run npm run watch from my terminal assets/styles/app.css will pull the styling from the Scss files

 

 

Scaling your component

If I didn’t convince you to use Twig yet I’ll do with the next feature.

As I wrote above to have a better chance to scale successfully your project you need small components.

These components must be reusable every time you need to.

Here is how simple Symfony make you do it.

Let’s say you have a section of your web page that need to show the user details (profile image, name, and emails.

Then, you can create a short Twig template like the following one.

< div class="user-profile">
    < img src="{{ user.profileImageUrl }}" alt="{{ user.fullName }}"/>
    < p>{{ user.fullName }} - {{ user.email }}
< /div>

 

And include this file on every page you need it to appear

 

{ # templates/blog/index.html.twig #}

{ # Stuff in this page #}
{ { include('blog/_user_profile.html.twig') }}
{ # Other stuff in this page #}

 

There you have it!

Simple, fast, and, most importantly, reusable.

 

Conclusion

Symfony has many components it has hundreds.

In this article, I have shown you the main one about the front-end structure.

how are you going to use them? did you already have a project in mind for learning these features?

If you like this content and you want to know more about PHP and Symfony in specific subscribe to the mail list and be notified when I new post comes out.

 
 
If you like this content and you are hungry for some more join the Facebook's community in which we share info and news just like this one!

Other posts that might interest you

Coding (Symfony) Dec 21, 2022

How to use Symfony messenger to consume RabbitMQ messages (with example)

See details
Coding (Symfony) Jan 20, 2023

10 Commands to Add a Database to Symfony

See details
Coding (Symfony) Feb 7, 2023

How to add forms in Symfony 6

See details
Get my free books' review to improve your skill now!
I'll do myself