Templates

This bundle come without theme, you can start reading the official Symfony documentation to create templates.

Twig Templating Language

The Twig templating language allows you to write concise, readable templates that are more friendly to web designers and, in several ways, more powerful than PHP templates. Take a look at the following Twig template example. Even if it's the first time you see Twig, you probably understand most of it:

<!DOCTYPE html>
<html>
    <head>
        <title>{{ blog.title|raw }}</title>
    </head>
    <body>
        <h1>{{ post.title }}</h1>

        {% if blog.user %}
            Hello {{ blog.user.nicename }}!
        {% endif %}

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

You can't run PHP code inside Twig templates, but Twig provides utilities to run some logic in the templates. For example, filters modify content before being rendered, like the upper filter to uppercase contents:

{{ post.title|upper }}

Creating Templates

Before explaining in detail how to create and render templates, look at the following example for a quick overview of the whole process. First, you need to create a new file in the templates/ directory to store the template contents:

{# templates/home.html.twig #}
<h1>{{ post.title }}!</h1>
<div>{{ post.excerpt|raw }}</div>

Then, create a controller that renders this template and passes to it the needed variables:

// src/Controller/BlogController.php
<?php

namespace App\Controller;

use Metabolism\WordpressBundle\Entity\Post;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class BlogController extends AbstractController
{
	public function homeAction(Post $post)
	{
		return $this->render('home.html.twig', ['post'=>$post]);
	}
}

Methods are called automatically if the provided routing is used, see Router page. To get action name, just click on Wordpress permalink, an error will display the expected method name :

InvalidArgumentException> The controller for URI "/" is not callable: Expected method "homeAction" on class "App\Controller\BlogController".

Last updated