Click here to Skip to main content
15,893,663 members
Articles / All Topics

Specify Route with Parameters in Twig

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
21 Nov 2016CPOL1 min read 4.4K   1  
Specify route with parameters in Twig

Introduction

Twig is an extremely powerful PHP templating language. For a student petition application (using Symfony framework) I was working on at Taft College, I needed to redirect to a route passing 2 parameters to use within the route controller. This is a post describing how to do that.

TWIG File

In my Twig file, I have a Table that shows various information from the petition. In one of the TD elements, I needed a “Change Program” link which would redirect to the change program controller passing in the student’s Banner ID (Banner is an Ellucian software product for Higher Education) and the student ID (the student identifier in my system).

The following Twig code shows how I achieved that:

PHP
<td><a href="{{ path('submitPetChangeProgram', 
{'banID':stu.getBanId, 'stuID':stu.getStuId}) }}">Change Program</a>
</td>

The “path” method specifies the route name to use, and I have in this case 2 parameters: banID, stuID. In the above code, stu is a student object (passed in from controller), and both getBanId and getStuId are methods of the Student Doctrine Entity.

Controller File

The controller file uses routing annotations to take care of routes. Below is the routing annotation I used:

PHP
/**
* @Route("/submitPetChangeProgram/{banID}/{stuID}",
* defaults={"banID" = 0,"stuID" = 0},
* name="submitPetChangeProgram")
*/
public function submitPetChangeProgramAction($banID, $stuID, Request $request){

Each of the parameters banID & stuID are optional, and the “defaults” keyword sets the default values. Now you can directly use $banID and $stuID variables directly in your controller.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Taft College
United States United States
I’m a software developer. Currently I’m working at Taft College as a Programmer.

Comments and Discussions

 
-- There are no messages in this forum --