1

I am currently including this at the top of every controller file:

$loader = new Twig_Loader_Filesystem('/templatedir/templates');

$twig = new Twig_Environment($loader, array('debug' => true));
$twig->addExtension(new Twig_Extension_Debug());

I find that placing this in every single file a bit redundant. Will there be any issues with placing this code in an external file and including it with a require_once command?

The render statement which follows in each controller file would make use of the $twig variable being included from the external file. I am a bit uncomfortable with accessing a variable from another file but am wondering if my concerns are justified.

kojow7
  • 10,308
  • 17
  • 80
  • 135
  • follow this http://rottmann.net/2013/01/setting-up-slim-php-framework-with-twig-templating/ may be helpful for you. and i do not know why you write the same code . Use container to put your twig instances & just called it from your controller. – jewelhuq Sep 10 '15 at 20:28

1 Answers1

1

To use require_once ist fine for a simple application. Your concerns are of course right, what if the variable $twig is set somewhere else too, in another include and another context? You would have a collision that is hard to debug.

There are several ways to avoid this problem. If you are familiar with object oriented programming, you could define a class like this:

File Twigloader.php

class Twigloader {
  public static $twig;

  public static function init() {
    $loader = new Twig_Loader_Filesystem('/templatedir/templates');

    self::$twig = new Twig_Environment($loader, array('debug' => true));
    self::$twig->addExtension(new Twig_Extension_Debug());
  }
}

Twigloader::init();

Now in each file you need twig you can do the following without the risk of a collision:

require_once "Twigloader.php";
$template = Twigloader::$twig->loadTemplate('test.html');

If you don't like require_once because in a complex application it is hard to keep track on the different dependencies you should look into autoloading: http://php.net/manual/de/language.oop5.autoload.php

Mario A
  • 3,286
  • 1
  • 17
  • 22