Symfony - View Engine


Advertisements


A View Layer is the presentation layer of the MVC application. It separates the application logic from the presentation logic.

When a controller needs to generate HTML, CSS, or any other content then, it forwards the task to the templating engine.

Templates

Templates are basically text files used to generate any text-based documents such as HTML, XML, etc. It is used to save time and reduce errors.

By default, templates can reside in two different locations −

app/Resources/views/ − The application's views directory can contain your application's layouts and templates of the application bundle. It also overrides third party bundle templates.

vendor/path/to/Bundle/Resources/views/ − Each third party bundle contains its templates in it's “Resources/views/” directory.

Twig Engine

Symfony uses a powerful templating language called Twig. Twig allows you to write concise and readable templates in a very easy manner. Twig templates are simple and won't process PHP tags. Twig performs whitespace control, sandboxing, and automatic HTML escaping.

Syntax

Twig contains three types of special syntax −

  • {{ ... }} − Prints a variable or the result of an expression to the template.

  • {% ... %} − A tag that controls the logic of the template. It is mainly used to execute a function.

  • {# ... #} − Comment syntax. It is used to add a single or multi-line comments.

The twig base template is located at “app/Resources/views/base.html.twig”.

Example

Let’s go through a simple example using twig engine.

StudentController.php

<?php  
namespace AppBundle\Controller;  

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Symfony\Component\HttpFoundation\Response; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller;  

class StudentController extends Controller { 
   /** 
      * @Route("/student/home") 
   */ 
   public function homeAction() { 
      return $this->render('student/home.html.twig'); 
   } 
}

Here, the render() method renders a template and puts that content into a Response object.

Now move to the “views” directory and create a folder “student” and inside that folder create a file “home.html.twig”. Add the following changes in the file.

home.html.twig

//app/Resources/views/student/home.html.twig  
<h3>Student application!</h3> 

You can obtain the result by requesting the url “http://localhost:8000/student/home”.

By default, Twig comes with a long list of tags, filters, and functions. Let’s go through one by one in detail.

Tags

Twig supports the following important tags −

Do

The do tag performs similar functions as regular expression with the exception that it doesn't print anything. Its syntax is as follows −

{% do 5 + 6 %} 

Include

The include statement includes a template and returns the rendered content of that file into the current namespace. Its syntax is as follows −

{% include 'template.html' %}

Extends

The extends tag can be used to extend a template from another one. Its syntax is as follows −

{% extends "template.html" %}

Block

Block acts as a placeholder and replaces the contents. Block names consists of alphanumeric characters and underscores. For example,

<title>{% block title %}{% endblock %}</title>

Embed

The embed tag performs a combination of both include and extends. It allows you to include another template's contents. It also allows you to override any block defined inside the included template, such as when extending a template. Its syntax is as follows −

{% embed “new_template.twig” %} 
   {# These blocks are defined in “new_template.twig" #} 
   {% block center %} 
      Block content 
   {% endblock %} 
{% endembed %} 

Filter

Filter sections allow you to apply regular Twig filters on a block of template data. For example,

{% filter upper %} 
   symfony framework 
{% endfilter %} 

Here, the text will be changed to upper case.

For

For loop fetches each item in a sequence. For example,

{% for x in 0..10 %} 
   {{ x }} 
{% endfor %}

If

The if statement in Twig is similar to PHP. The expression evaluates to true or false. For example,

{% if value == true %} 
   <p>Simple If statement</p> 
{% endif %}

Filters

Twig contains filters. It is used to modify content before being rendered. Following are some of the notable filters.

Length

The length filter returns the length of a string. Its syntax is as follows −

{% if name|length > 5 %} 
   ... 
{% endif %} 

Lower

The lower filter converts a value to lowercase. For example,

{{ 'SYMFONY'|lower }}

It would produce the following result −

symfony

Similarly, you can try for upper case.

Replace

The replace filter formats a given string by replacing the placeholders. For example,

{{ "tutorials point site %si% and %te%."|replace({'%si%': web, '%te%': "site"}) }} 

It will produce the following result −

tutorials point website 

Title

The title filter returns a titlecase version of the value. For example,

{{ 'symfony framework '|title }}

It will produce the following result −

 Symfony Framework

Sort

The sort filter sorts an array. Its syntax is as follows −

{% for user in names|sort %} 
   ... 
{% endfor %}

Trim

The trim filter trims whitespace (or other characters) from the beginning and the end of a string. For example,

{{ '  Symfony!  '|trim }} 

It will produce the following result −

Symfony!

Functions

Twig supports functions. It is used to obtain a particular result. Following are some of the important Twig functions.

Attribute

The attribute function can be used to access a “dynamic” attribute of a variable. Its syntax is as follows −

{{ attribute(object, method) }} 
{{ attribute(object, method, arguments) }} 
{{ attribute(array, item) }} 

For example,

{{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }}

Constant

Constant function returns the constant value for a specified string. For example,

{{ constant('Namespace\\Classname::CONSTANT_NAME') }}

Cycle

The cycle function cycles on an array of values. For example,

{% set months = [‘Jan’, ‘Feb’, ‘Mar’] %}  
{% for x in 0..12 %} 
   { cycle(months, x) }} 
{% endfor %}

Date

Converts an argument to a date to allow date comparison. For example,

<p>Choose your location before {{ 'next Monday'|date('M j, Y') }}</p> 

It will produce the following result −

Choose your location before May 15, 2017

The argument must be in one of PHP’s supported date and time formats.

You can pass a timezone as the second argument.

Dump

The dump function dumps information about a template variable. For example,

{{ dump(user) }}

Max

The max function returns the largest value of a sequence. For example,

{{ max(1, 5, 9, 11, 15) }}

Min

The min function returns the smallest value of a sequence. For example,

{{ min(1, 3, 2) }}

Include

The include function returns the rendered content of a template. For example,

{{ include('template.html') }}

Random

The random function generates a random value. For example,

{{ random([‘Jan’, ‘Feb’, ‘Mar’, ‘Apr’]) }} 
{# example output: Jan #} 

Range

Range function returns a list containing an arithmetic progression of integers. For example,

{% for x in range(1, 5) %} 
   {{ x }}, 
{% endfor %} 

It will produce the following result −

1,2,3,4,5

Layouts

A Layout represents the common parts of multiple views, i.e. for example, page header, and footer.

Template Inheritance

A template can be used by another one. We can achieve this using template inheritance concept. Template inheritance allows you to build a base “layout” template that contains all the common elements of web site defined as blocks.

Let’s take a simple example to understand more about template inheritance.

Example

Consider the base template located at “app/Resources/views/base.html.twig”. Add the following changes in the file.

base.html.twig

<!DOCTYPE html> 
<html> 
   <head> 
      <meta charset = "UTF-8"> 
      <title>{% block title %}Parent template Layout{% endblock %}</title> 
   </head> 
</html>

Now move to the index template file located at “app/Resources/views/default/index.html.twig“. Add the following changes in it.

index.html.twig

{% extends 'base.html.twig' %}  
{% block title %}Child template Layout{% endblock %}

Here, the {% extends %} tag informs the templating engine to first evaluate the base template, which sets up the layout and defines the block. The child template is then rendered. A child template can extend the base layout and override the title block. Now, request the url “http://localhost:8000” and you can obtain its result.

Assets

The Asset manages URL generation and versioning of web assets such as CSS stylesheets, JavaScript files, and image files.

JavaScript

To include JavaScript files, use the javascripts tag in any template.

{# Include javascript #} 
{% block javascripts %} 
   {% javascripts '@AppBundle/Resources/public/js/*' %} 
      <script src="{{ asset_url }}"></script> 
   {% endjavascripts %} 
{% endblock %} 

Stylesheets

To include stylesheet files, use the stylesheets tag in any template

{# include style sheet #} 
{% block stylesheets %} 
   {% stylesheets 'bundles/app/css/*' filter = 'cssrewrite' %} 
      <link rel = "stylesheet" href="{{ asset_url }}" />
   {% endstylesheets %} 
{% endblock %}

Images

To include an image, you can use the image tag. It is defined as follows.

{% image '@AppBundle/Resources/public/images/example.jpg' %} 
   <img src = "{{ asset_url }}" alt = "Example" /> 
{% endimage %} 

Compound Assets

You can combine many files into one. This helps to reduce the number of HTTP requests, and produces greater front-end performance.

{% javascripts 
   '@AppBundle/Resources/public/js/*' 
   '@AcmeBarBundle/Resources/public/js/form.js' 
   '@AcmeBarBundle/Resources/public/js/calendar.js' %} 
   <script src = "{{ asset_url }}"></script> 
{% endjavascripts %}


Advertisements