Bootstrap themed forms with Silex – UPDATE

In a side-project using Silex I wanted to have forms being styled with Bootstrap. I did not want to write the theming code myself. Since I couldn’t find a solution for Silex itself I thought about re-using a Symfony solution.

Here is what I am using now:

First I added the Braincrafted/BootstrapBundle to the composer.json:

"braincrafted/bootstrap-bundle": "2.0.0"

In my apps bootstrap.php I added a path to the Twig configuration and registered a Twig extension:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => array(
        __DIR__.'/views',
        __DIR__.'/../vendor/braincrafted/bootstrap-bundle/Braincrafted/Bundle/BootstrapBundle/Resources/views/Form'
    )    
));
...
$app['twig'] = $app->share($app->extend('twig', function($twig) {
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapIconExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapLabelExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapBadgeExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapFormExtension);
    return $twig;
}));

In the forms template the theme is registered:

{% form_theme form 'bootstrap.html.twig' %}

From now on the form on the page is rendered nicely in Bootstrap-style.

UPDATE (24.4.2014): As mentioned in the comments – with the latest updates – now some more extensions are needed. The code example has been updated (hat tip gcrico).

Advertisements
This entry was posted in PHP and tagged , , . Bookmark the permalink.

2 Responses to Bootstrap themed forms with Silex – UPDATE

  1. gcrico says:

    More Twig extensions are needed!

    $app[‘twig’] = $app->share($app->extend(‘twig’, function($twig, $app) {
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapIconExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapLabelExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapBadgeExtension);
    $twig->addExtension(new \Braincrafted\Bundle\BootstrapBundle\Twig\BootstrapFormExtension);
    return $twig;
    }));

  2. You just need to define form_theme variable like this:
    {% form_theme form ‘bootstrap_3_layout.html.twig’ %}
    before form call in your template
    http://symfony.com/blog/new-in-symfony-2-6-bootstrap-form-theme

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s