Shiva Acharjee Shiva Acharjee - 2 months ago 14x
Twig Question

Using php code in .twig file slim framework

I am using Slim Framework for the first time and also using twig for templatizing. I have a land.twig file the contents of that file are

<form action="index.html" method="get">
<div class="form-group">
<input type="text" class="form-control" placeholder="Full Name">

I also have a string file to support multi-language and the way I call the string for translation is lang("some_string");. The land.twig file is rendered by a controller. My question is how can I add lang("some_string") within placeholder attribute for html elements in that twig file ?


You could use Twig_SimpleFilter.

require_once '/path/to/lib/Twig/Autoloader.php';

$loader = new Twig_Loader_Filesystem('/path/to/templates');
// an anonymous function
$filter = new Twig_SimpleFilter('lang', function ($string) {
    //do stuff
    return $string;

$twig = new Twig_Environment($loader);

Then in your template you can use

 <input type="text" class="form-control" placeholder="{{ 'Full Name'|lang }}">

Since you are using slim and its twig integration you have to add the filter within the twig component.

// Register component on container
$container['view'] = function ($container) {
   $view = new \Slim\Views\Twig('path/to/templates', [
       'cache' => 'path/to/cache'
    $view->addExtension(new \Slim\Views\TwigExtension(

    $filter = new Twig_SimpleFilter('lang', function ($string) {
        //do stuff
        return $string;


    return $view;

Other than that twig has a i18n extension.