How to passing data from a page to a .twig Template
1. Create in src\AppBundle\Controller\LuckyController.php
<?php // src/AppBundle/Controller/LuckyController.php namespace AppBundle\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; use Symfony\Bundle\FrameworkBundle\Controller\Controller; // to extend Controller class LuckyController extends Controller // extends Controllers of Symfony { /** * @Route("/lucky/number") */ public function numberAction() // my function { $number = mt_rand(0, 100); // random PHP function // send the variable to a .twig template return $this->render('lucky/number.html.twig', array( 'number' => $number, )); } }
2. Create in app\Resources\views\lucky\number.html.twig
{# app/Resources/views/lucky/number.html.twig #} <h1>Your lucky number is {{ number }}</h1>
NOTICE:
a. The namespace to exted standard Controller of Symfony:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
b. The class have to extend the Controller namespace:
class LuckyController extends Controller
c. render using lucky/number.html.twig the array key ‘number’ with value $number
return $this->render(‘lucky/number.html.twig’, array(
‘number’ => $number,
d. the template receive the value of number
<h1>Your lucky number is {{ number }}</h1> {{ number }} -> this is the syntax of .twig to get the value sent by public function numberAction() {# app/Resources/views/lucky/number.html.twig #} -> this is a comment only in .twig syntax