Loop list in batches using Twig (or plain PHP)

Recently I had to loop through a series of elements in a WordPress template (thanks Timber), which happened to be using Bootstrap.

If you ever used Bootstrap, you are familiar with the following markup:

The problem here is very common. You have to:

  • Loop every 3/4/n items.
  • Insert a separator or whatever every 3/4/n items.

You can achieve this with modulo (divisibleby) and checking if the loop index is last and other weird magic. However, Twig introduced the batch filter in version 1.12.3, where you can make this much less cumbersome.

So, adapting the current example and their docs, this is how we achieve a clean loop:

Much better, right?

I realized PHP has a built-in function that handles this. It’s called array_chunk which, of course, splits an array into chunks (or batches as I recalled, and the reason why I hadn’t been able to find it on the docs.)

Edit 19 Jul: Added plain PHP version.

Build a simple website with Silex

I love static* websites. They’re usually faster to develop, smaller, require no database or backend and are faster to load. Of course they require more work to maintain and tweak at first, but if you’re a developer, these things should be pretty entertaining or at the very least, straightforward.

There are many options out there for building static websites; both free, like Anchor, Sculpin and Stacey; and paid, like Kirby and Statamic, among many others, like Silex.

This is a good moment to tell you that I’m aware of the difference of static websites vs flat-file CMSs vs micro-frameworks.

While I love the infinite possibilities of full-fledged CMSs and the blazing speed and simplicity of full-static websites, I feel that on most cases a good middle point is useful. That’s why I frequently choose micro-frameworks (or flat-file CMSs) over full CMSs or static site generators. One gives too many options, the other is too restrictive.

Silex is “a PHP micro-framework built on the shoulders of Symfony2 and Pimple and also inspired by Sinatra.”

It’s really simple to put together a simple website running Silex.

First, run composer init to start your project.

Then add silex/silex and twig-bridge, to use the Twig templating engine:

    "require": {
        "silex/silex": "^1.2",
        "symfony/twig-bridge": "^2.6"

Then just run composer install on a Terminal.

After that, all your dependencies should be sitting in your /vendor’s app directory.

Create an index.php file with this contents:

require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$app = new Silex\Application();

// $app['debug'] = true;

$app->register(new Silex\Provider\UrlGeneratorServiceProvider());

// Register Twig provider and define a path for twig templates
$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/views',

// Home page
$app->get('/', function() use($app) {
    return $app['twig']->render('index.html');

// Other page
$app->get('/other', function() use($app) {
    return $app['twig']->render('other.html');

// 404 - Page not found
$app->error(function (\Exception $e, $code) use ($app) {
    switch ($code) {
        case 404:
          return $app['twig']->render('404.html');
            $message = 'The requested page could not be found.';
            $message = 'We are sorry, but something went terribly wrong.';

    return new Response($message);


This bootstraps Silex. Here I declared two routes: / (home) and /other, which load the views index.html and other.html respectivly, on the /views folder.

That’s it! Following the same pattern, you can define as many pages as you wish.

If you need to do more complicated stuff like sending e-mails, do some logging or build forms, you can check the Silex documentation.


Laravel Homestead: multiple projects, one VM

Vagrant is great to isolate a development environment inside a VM. However, after a while you can find you have a bunch of heavy VMs that share the same characteristics, each one for a simple PHP project.

Enter Laravel Homestead

In these cases, you can safely use Laravel Homestead. Homestead is a Vagrant box pre-configured with an Nginx web server, PHP 5.6, MySQL, Postgres, Redis, Memcached, and other stuff to make development easier and faster.

The documentation is pretty clear and in a few steps you can have a working development environment, where you can add multiple projects.

Chek it out: Laravel Homestead

Update: Also, I recently found a simple guide on how to install MailCatcher on Homestead, which is really useful: Installing MailCatcher in Laravel Homestead

Run a simple HTTP server with one command line

Recently someone told me this great and simple trick on how to run an HTTP web server with just one command line. This is useful for a million things, but I use it for prototyping and avoid same-origin policy in Chrome. Sure, I know there’s a way to disable it, but you may not want to do that.

XMLHttpRequest cannot load file:///C:/Projects/Test/app/views/shell.html. Cross origin requests are only supported for HTTP.

This is all it takes:

$ cd /projects/TestProject
$ python -m SimpleHTTPServer 1234

Then you can access your files at localhost:1234.

I think this provides a much real environment while you build your HTML/JS. That way, you can have a more accurate preview on how your UI is going to feel when served through the Internet by a real server.

Note: This can also be achieved using PHP and probably a gazillion other programming languages.

Doctrine 2

Últimamente estuve trabajando bastante con CodeIgniter en conjunto con el ORM de Doctrine 1.2 para simplificar el acceso a datos y dar más poder que el Active Record que implementa el framework.

Hoy me topé con una presentación muy interesante de lo que traerá la versión 2, que aprovecha todo el potencial de PHP 5.3.

Una de las cosas más novedosas es el uso de namespaces y “annotations” para declarar una clase como entidad, sin tener que extender de una clase base:


namespace Entities; 

/** * @Entity @Table(name="users") */
class User {

	/** @Id @Column(type="integer") @GeneratedValue */
	private $id; 

	/** @Column(length=50) */
	private $name; 

	/** @OneToOne(targetEntity="Address") */
	private $address; 


Más información

Nace CodeIgniter Reactor

CodeIgniter LogoEllisLab, Inc., la empresa responsable y creadora de el framework PHP CodeIgniter anunció que a partir de el año que viene el desarrollo del mismo se dividirá en dos ramas:

CodeIgniter Core será mantenida por la empresa e incorporará cambios de la segunda rama, a un ritmo más lento, para adaptarse al ambiente empresarial.

CodeIgniter Reactor será la rama mantenida por la comunidad, guiada por seis ingenieros voluntarios y apadrinada por EllisLab. Esta rama tendrá un desarrollo más dinámico.

Eventualmente los cambios implementados en Reactor se implementarían en Core, una vez que estén suficientemente probados y sean aceptados por la empresa.

Para comenzar a contribuír con el proyecto, basta con entrar al espacio de CodeIgniter Reactor que crearon sobre la plataforma de UserVoice y comenzar a darle peso a las funcionalidades que creemos que hacen falta: CodeIgniter Reactor (UserVoice).

Más información

  • http://codeigniter.com/news/codeigniter_in_2011_reactor_core_uservoice/
  • http://codeigniter.uservoice.com

URLs amigables en XAMPP

Un requerimiento común para las aplicaciones de hoy en día es utilizar urls amigables. Para lograr esto en XAMPP hay que seguir unos pocos pasos.

Para poder utilizar urls amigables bajo XAMPP hay que habilitar el módulo mod_rewrite de Apache. Para esto debemos:

Editar el archivo httpd.conf que se encuentra en el directorio [instalación_xampp]/apache/conf. Por defecto instalación_xampp es C:\xampp.

Des-comentar la línea:
#LoadModule rewrite_module modules/mod_rewrite.so

Quedaría así:
LoadModule rewrite_module modules/mod_rewrite.so

Por úlltimo, buscar las apariciones del texto AllowOverride None y sustituir por AllowOverride All.

Luego solo falta reiniciar el servidor y por supuesto, tener nuestra aplicación configurada para aprovechar esta funcionalidad.

Fuente: Murfitt.net http://murfitt.net/blog/dan/2007/10/04/xampp-and-modrewrite-getting-clean-urls-work