Quick tip: Symfony2 dynamic templates

Past entries

Hello everyone,

This article should be the first of many more frequent ones, because I've started using Symfony 2.

Symfony
Click to visit Symfony's website

If you don't know Symfony, just know that it's a PHP framework (created by a french guy) that enables you to create websites very fast and easily. I've had some experience developing websites with PHP without any frameworks or libraries, and I tried Zend Framework several years ago, but I was never convinced by this way of coding.
Now that I discovered Symfony, I don't think I will ever stop using frameworks (excepted for small projects). If you haven't tried yet, this could be the time.

As I'm currently working on converting my portfolio to Symfony 2 (and maybe distributing it, but I'll see that later), I will probably share some quick tips which could be useful for developers. So today I'm just going to show you how to make templates go dynamic.

Quick tip : dynamic templates

On many sites, there are dynamic parts that are on several pages, like dynamic menus. For instance, on my portfolio, the projects categories in the menu are dynamically loaded. You can also imagine other similar situations.

The problem is that you can't just manually load it on every action of the site. This wouldn't be a proper way of coding, and the smallest change would need every actino of every controller to be changed.

So here how to include dynamic parts of a template :

  1. Put the following code in your Twig template :
    {% render "NameOfTheBundle:Controller:dynamic" %}
  2. Then create the corresponding action in your controller, which will render a template :
        public function dynamicAction(){
            // ... Getting dynamic data ...
            $dynamic_array = ...
            
            // Rendering the dynamic template
            return $this->render('NameOfTheBundle:ViewName:dynamic.html.twig',array(
                'dynamic_array' => $dynamic_array
            ));
        }
  3. Finally, create the dynamic.html.twig template :
    {% for element in dynamic_array %}
        {{ element.attribute }}
        <br />
    {% endfor %}

It's as simple as that !

Other news

At the moment, I am spending a lot of my spare time on unversity homework and other stuff, which means I won't be starting many new projects (at least not until the new version of my portfolio is online). When it's ready, I will post another article about a new Flash game I'm working on (developing Flash games is so much fun :-p ).

By the way, don't forget to check my latest project : Alien Killer.

< Switched to Symfony2 & random news
Ubuntu 11.10 released >