addGlobal() public method

Registers a Global.
public addGlobal ( string $name, mixed $value )
$name string The global name
$value mixed The global value
Exemplo n.º 1
0
 /**
  * Sets up Twig ready for use and returns it
  * @return \Twig_Environment
  */
 protected function getTwigEnvironment()
 {
     /**
      * Get the config
      * @var \snb\config\ConfigInterface $config
      */
     $config = $this->container->get('config');
     $kernel = $this->container->get('kernel');
     // Find the cache path
     $cachePath = $config->get('twig.cache', ':/cache');
     // Use our loader the know how to map resource names to filenames
     $loader = new TwigFileLoader($this->container);
     // use the default environment. Should pass settings over from the config
     $twig = new \Twig_Environment($loader, array('cache' => $kernel->findPath($cachePath), 'debug' => $kernel->isDebug()));
     // Add the dump command (only works when debug is true)
     $twig->addExtension(new \Twig_Extension_Debug());
     // Add the app as a global...
     $twig->addGlobal('app', $kernel);
     // Add all the extensions that have been registered with the service provider
     $globals = $this->container->getMatching('twig.global.*');
     foreach ($globals as $global) {
         if ($global instanceof ViewGlobalInterface) {
             $twig->addGlobal($global->getGlobalName(), $global);
         }
     }
     // Add all the extensions that have been registered with the service provider
     $extensions = $this->container->getMatching('twig.extension.*');
     foreach ($extensions as $ext) {
         $twig->addExtension($ext);
     }
     return $twig;
 }
Exemplo n.º 2
0
 public static function view($modules = NULL)
 {
     include_once __ROOT__ . 'vendor/autoload.php';
     $views = __VIEWS__;
     if (__ENV_MODE__ == "dev") {
         $cache = false;
     } else {
         $cache = true;
     }
     $loader = new \Twig_Loader_Filesystem($views);
     // Dossier contenant les templates
     if ($cache) {
         $twig = new \Twig_Environment($loader, array('debug' => false, 'cache' => $views . '/cache/', 'auto_reload' => true));
     } else {
         $twig = new \Twig_Environment($loader, array('debug' => true));
     }
     $twig->addExtension(new \Twig_Extensions_Extension_Text());
     $twig->addExtension(new \Twig_Extensions_Extension_I18n());
     $twig->addExtension(new \Twig_Extensions_Extension_Intl());
     $twig->addExtension(new \Twig_Extensions_Extension_Array());
     $twig->addExtension(new \Twig_Extensions_Extension_Date());
     $twig->addGlobal('app_name', __NAME_APPLICATION__);
     $path = array('views' => $views, 'url' => __URL_LOCAL__, 'bootstrap' => __BOOTSTRAP__);
     $twig->addGlobal('path', $path);
     $route = array('only' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     $twig->addGlobal('route', $route);
     return $twig;
 }
Exemplo n.º 3
0
 public function getTwig($configuration)
 {
     $templateDir = $this->getRootPath() . '/src/DavM85/BusFactor/Resources/views';
     $loader = new \Twig_Loader_Filesystem($templateDir);
     $twig = new \Twig_Environment($loader, array());
     $twig->addGlobal('rootPath', $configuration['targetDir'] . '/');
     $twig->addGlobal('lower', $configuration['lower_threshold']);
     $twig->addGlobal('higher', $configuration['higher_threshold']);
     $filter = new \Twig_SimpleFilter('level', function ($percent) use($configuration) {
         $lower = $configuration['lower_threshold'];
         $higher = $configuration['higher_threshold'];
         if ($percent == 0) {
             return '';
         } elseif ($percent < $lower) {
             return 'success';
         } elseif ($percent >= $lower && $percent < $higher) {
             return 'warning';
         } else {
             return 'danger';
         }
     });
     $twig->addFilter($filter);
     // @todo dont know why I left that here
     $common = array('id' => '', 'full_path' => '', 'path_to_root' => '', 'breadcrumbs' => '', 'date' => '', 'version' => '', 'runtime_name' => '', 'runtime_version' => '', 'runtime_link' => '', 'generator' => '', 'low_upper_bound' => '', 'high_lower_bound' => '');
     return $twig;
 }
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     if (!in_array($this->type, array('form', 'filter'))) {
         throw new \Exception('Please override $this->type in your test class specifying template to use (either form or filter)');
     }
     $rendererEngine = new TwigRendererEngine(array($this->type . '_admin_fields.html.twig'));
     $csrfManagerClass = interface_exists('Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface') ? 'Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface' : 'Symfony\\Component\\Form\\Extension\\Csrf\\CsrfProvider\\CsrfProviderInterface';
     $renderer = new TwigRenderer($rendererEngine, $this->getMock($csrfManagerClass));
     $this->extension = new FormExtension($renderer);
     $twigPaths = array(__DIR__ . '/../../../Resources/views/Form');
     //this is ugly workaround for different build strategies and, possibly,
     //different TwigBridge installation directories
     if (is_dir(__DIR__ . '/../../../vendor/symfony/twig-bridge/Resources/views/Form')) {
         $twigPaths[] = __DIR__ . '/../../../vendor/symfony/twig-bridge/Resources/views/Form';
     } elseif (is_dir(__DIR__ . '/../../../vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form')) {
         $twigPaths[] = __DIR__ . '/../../../vendor/symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form';
     } else {
         $twigPaths[] = __DIR__ . '/../../../../../symfony/symfony/src/Symfony/Bridge/Twig/Resources/views/Form';
     }
     $loader = new StubFilesystemLoader($twigPaths);
     $this->environment = new \Twig_Environment($loader, array('strict_variables' => true));
     $this->environment->addGlobal('sonata_admin', $this->getSonataAdmin());
     $this->environment->addExtension(new TranslationExtension(new StubTranslator()));
     $this->environment->addExtension($this->extension);
     $this->extension->initRuntime($this->environment);
 }
Exemplo n.º 5
0
 /**
  * @return array[string => mixed]
  */
 public static function before()
 {
     $user = null;
     // initialize session
     Session::init();
     // setup twig
     $twig = new \Twig_Environment(new \Twig_Loader_Filesystem());
     $twig->getLoader()->addPath(__DIR__ . '/Twig');
     $twig->addGlobal('asset', Settings::load('settings')->get('asset-url'));
     $twig->addGlobal('base_url', NekoPHP::getBaseUrl());
     // add the current user object to twig, if it exists
     $user_id = Session::get('user_id');
     // set the user if a user_id is set
     if ($user_id > 0) {
         $user = new \NekoPHP\Modules\User\Models\User($user_id);
         $twig->addGlobal('cuser', $user);
     }
     // add one-time alerts
     foreach (['success', 'info', 'warning', 'error'] as $alert) {
         if (Session::existsOnce($alert)) {
             $twig->addGlobal('alert_' . $alert, Session::getOnce($alert));
         }
     }
     return ['cuser' => $user, 'twig' => $twig];
 }
 protected function setUp()
 {
     if (!class_exists('Symfony\\Component\\Locale\\Locale')) {
         $this->markTestSkipped('The "Locale" component is not available');
     }
     if (!class_exists('Symfony\\Component\\EventDispatcher\\EventDispatcher')) {
         $this->markTestSkipped('The "EventDispatcher" component is not available');
     }
     if (!class_exists('Symfony\\Component\\Form\\Form')) {
         $this->markTestSkipped('The "Form" component is not available');
     }
     if (!class_exists('Twig_Environment')) {
         $this->markTestSkipped('Twig is not available.');
     }
     parent::setUp();
     $rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig', 'custom_widgets.html.twig'));
     $renderer = new TwigRenderer($rendererEngine, $this->getMock('Symfony\\Component\\Form\\Extension\\Csrf\\CsrfProvider\\CsrfProviderInterface'));
     $this->extension = new FormExtension($renderer);
     $loader = new StubFilesystemLoader(array(__DIR__ . '/../../Resources/views/Form', __DIR__));
     $environment = new \Twig_Environment($loader, array('strict_variables' => true));
     $environment->addExtension(new TranslationExtension(new StubTranslator()));
     $environment->addGlobal('global', '');
     // the value can be any template that exists
     $environment->addGlobal('dynamic_template_name', 'child_label');
     $environment->addExtension($this->extension);
     $this->extension->initRuntime($environment);
 }
Exemplo n.º 7
0
 public function __construct(\Twig_Environment $twig = null, array $config = array())
 {
     if ($twig) {
         $this->twig = $twig;
         $this->twig->addGlobal('ctrl_rad_templates', $config['templates']);
     }
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$event->isMasterRequest() || '/' !== $request->getPathInfo()) {
         return;
     }
     $this->twig->addGlobal('random_quote_event', $this->quoteRepository->findRandom());
 }
Exemplo n.º 9
0
 /**
  * 新增模板所需要的一些常量
  * @param \Twig_Environment $twig
  */
 protected function addGlobal(\Twig_Environment $twig)
 {
     //添加常用的全局变量
     $twig->addGlobal('__CSS__', BASEDIR . '/App/Public/css');
     $twig->addGlobal('__JS__', BASEDIR . '/App/Public/js');
     $twig->addGlobal('__IMAGE__', BASEDIR . '/App/Public/image');
     $twig->addGlobal('STATIC_PATH', '/public');
     $twig->addGlobal('IMG_PATH', '/public/images');
 }
Exemplo n.º 10
0
 /**
  * Initialize a new View
  *
  * @param $file
  */
 public function __construct($file, $data = null)
 {
     $this->file = $file;
     $this->data = $data;
     $twigLoader = new Twig_Loader_Filesystem(INC_ROOT . '/app/views', '__main__');
     $this->twig = new Twig_Environment($twigLoader, ['cache' => INC_ROOT . '/app/cache']);
     $this->twig->addGlobal('ASSET_ROOT', ASSET_ROOT);
     $this->twig->addGlobal('HTTP_ROOT', HTTP_ROOT);
 }
Exemplo n.º 11
0
 protected function render($array = [])
 {
     $this->twig->addGlobal("request_path", $this->requestStack->getCurrentRequest()->getPathInfo());
     $calleeClass = get_called_class();
     $calleeMethod = debug_backtrace()[1]['function'];
     $exploded = explode("\\", $calleeClass);
     $calleeFinalPart = implode("/", array_merge(array_slice($exploded, 3, count($exploded) - 4), [str_replace("Controller", "", end($exploded))]));
     $templateFilename = $calleeFinalPart . "/" . $calleeMethod . ".twig";
     return $this->twig->render($templateFilename, $array);
 }
Exemplo n.º 12
0
 /**
  * Constructor
  *
  * @param string $templateDir
  * @param bool $cacheDir
  *
  * @throws TemplateDirectoryNotFoundException
  */
 public function __Construct($templateDir, $cacheDir = false)
 {
     if (realpath($templateDir) === false) {
         throw new TemplateDirectoryNotFoundException(sprintf('template directory not found in "%s"', $templateDir));
     }
     $this->application = Application::getInstance();
     $this->loader = new \Twig_Loader_Filesystem($templateDir);
     $this->template = new \Twig_Environment($this->loader, array('cache' => $cacheDir, 'auto_reload' => true, 'strict_variables' => true));
     $this->template->addGlobal('app', $this->application);
 }
Exemplo n.º 13
0
 public static function getTwig()
 {
     if (!self::$twig) {
         \Twig_Autoloader::register();
         $cache = Config::get('cache') ? Config::get('cache') . '/' : false;
         $loader = new \Twig_Loader_Filesystem(Config::get('views') . '/');
         $twig = new \Twig_Environment($loader, array('cache' => $cache, 'debug' => Config::get('debug')));
         // Add globals
         $twig->addGlobal('session', Session::getInstance());
         $twig->addGlobal('url', new URL());
         self::$twig = $twig;
     }
     return self::$twig;
 }
Exemplo n.º 14
0
 /**
  * Metodo Privado
  * EjecutarPlantillaDesarrollo($Parametros)
  * 
  * Carga la plantilla correspondiente
  * @access private
  */
 private function EjecutarPlantillaDesarrollo($Parametros = array())
 {
     self::ValidarEjecutarTwig();
     $TwigLoader = new Twig_Loader_Filesystem(implode(DIRECTORY_SEPARATOR, array(__SysNeuralFileRootLibNeural__, self::$FolderErrores, self::$FolderAlertas)));
     $TwigEnvironment = new Twig_Environment($TwigLoader, array('charset' => 'UTF-8'));
     if (defined('APPNEURALPHPHOST') == true) {
         $TwigEnvironment->addGlobal('NeuralRutaApp', implode('/', array(__NeuralUrlRaiz__)));
         $TwigEnvironment->addGlobal('NeuralRutaWebPublico', implode('/', array(__NeuralUrlRaiz__, 'WebRoot', 'ErroresWeb')));
     } else {
         $TwigEnvironment->addGlobal('NeuralRutaBase', __NeuralUrlRaiz__);
         $TwigEnvironment->addGlobal('NeuralRutaWebPublico', implode('/', array(__NeuralUrlRaiz__, 'Web')));
     }
     echo $TwigEnvironment->render($Parametros['Plantilla'], array('Titulo' => $Parametros['Titulo'], 'Informacion' => $Parametros['Informacion'], 'Aplicacion' => $Parametros['Aplicacion'], 'Modulo' => $Parametros['Modulo'], 'Controlador' => $Parametros['Controlador'], 'Metodo' => $Parametros['Metodo'], 'Server' => $_SERVER, 'PHP' => array('VERSION' => phpversion(), 'MEMORY' => memory_get_usage(), 'OS' => php_uname('s'), 'MACHINE' => php_uname('m'), 'NAME_SERVER' => gethostbyaddr($_SERVER['SERVER_ADDR']))));
 }
 protected function setUp()
 {
     parent::setUp();
     $loader = new StubFilesystemLoader(array(__DIR__ . '/../../Resources/views/Form', __DIR__ . '/Fixtures/templates/form'));
     $environment = new \Twig_Environment($loader, array('strict_variables' => true));
     $environment->addExtension(new TranslationExtension(new StubTranslator()));
     $environment->addGlobal('global', '');
     // the value can be any template that exists
     $environment->addGlobal('dynamic_template_name', 'child_label');
     $environment->addExtension(new FormExtension());
     $rendererEngine = new TwigRendererEngine(array('form_div_layout.html.twig', 'custom_widgets.html.twig'), $environment);
     $this->renderer = new TwigRenderer($rendererEngine, $this->getMock('Symfony\\Component\\Security\\Csrf\\CsrfTokenManagerInterface'));
     $this->registerTwigRuntimeLoader($environment, $this->renderer);
 }
Exemplo n.º 16
0
function template_fill($template_name, $vars = array())
{
    $loader = new Twig_Loader_Filesystem('templates');
    $twig = new Twig_Environment($loader, array('cache' => false, 'autoescape' => true, 'autoreload' => true));
    $class = new ReflectionClass($twig);
    $methods = $class->getMethods();
    $twig->addGlobal('get', $_GET);
    $twig->addGlobal('post', $_POST);
    $twig->addGlobal('request', $_REQUEST);
    $twig->addGlobal('session', $_SESSION);
    $callback_values = process_callbacks(template_callbacks());
    $vars = array_merge($callback_values, $vars);
    $template = $twig->loadTemplate($template_name . ".html");
    return $template->render($vars);
}
Exemplo n.º 17
0
 /**
  * Get Twig-instance
  *
  * @return Twig_Environment
  */
 protected static function getTwig()
 {
     if (!static::$twig) {
         $loader = new \Twig_Loader_Filesystem(PATH_APP . '/views');
         static::$twig = new \Twig_Environment($loader, array('cache' => MAIN_SERVER ? PATH_DATA . '/twig-cache' : null, 'strict_variables' => true, 'autoescape' => false));
         static::$twig->getExtension('core')->setNumberFormat(2, ',', ' ');
         static::$twig->addExtension(new \Kofradia\Twig\Date());
         static::$twig->addExtension(new \Kofradia\Twig\Counter());
         static::$twig->addExtension(new \Kofradia\Twig\Render());
         static::$twig->addExtension(new \Kofradia\Twig\Helpers());
         static::$twig->addGlobal("page", \ess::$b->page);
         static::$twig->addGlobal("helper", new \Kofradia\Twig\TemplateHelper());
     }
     return static::$twig;
 }
 public function readIntoWidgetRouteParameters(Widget $widget)
 {
     $entity = $widget->getEntity();
     //Creates a new twig environment
     $twig = new \Twig_Environment(new \Twig_Loader_String());
     //add global values for `entity` and `businessEntityId`
     $twig->addGlobal('entity', $entity);
     $twig->addGlobal($widget->getBusinessEntityId(), $entity);
     //Interpret variables in widget route parameters to be able to generate correct
     $params = array();
     foreach ($widget->getLink()->getRouteParameters() as $key => $_routeParameter) {
         $params[$key] = $twig->render($_routeParameter);
     }
     $widget->getLink()->setRouteParameters($params);
 }
Exemplo n.º 19
0
 /**
  * @dataProvider getTests
  */
 public function testIntegration($file, $message, $condition, $templates, $exception, $outputs)
 {
     if ($condition) {
         eval('$ret = ' . $condition . ';');
         if (!$ret) {
             $this->markTestSkipped($condition);
         }
     }
     $loader = new Twig_Loader_Array($templates);
     foreach ($outputs as $match) {
         $config = array_merge(array('cache' => false, 'strict_variables' => true), $match[2] ? eval($match[2] . ';') : array());
         $twig = new Twig_Environment($loader, $config);
         $twig->addExtension(new TestExtension());
         $twig->addExtension(new Twig_Extension_Debug());
         $policy = new Twig_Sandbox_SecurityPolicy(array(), array(), array(), array(), array());
         $twig->addExtension(new Twig_Extension_Sandbox($policy, false));
         $twig->addGlobal('global', 'global');
         try {
             $template = $twig->loadTemplate('index.twig');
         } catch (Exception $e) {
             if (false !== $exception) {
                 $this->assertEquals(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
                 return;
             }
             if ($e instanceof Twig_Error_Syntax) {
                 $e->setTemplateFile($file);
                 throw $e;
             }
             throw new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
         }
         try {
             $output = trim($template->render(eval($match[1] . ';')), "\n ");
         } catch (Exception $e) {
             if (false !== $exception) {
                 $this->assertEquals(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage())));
                 return;
             }
             if ($e instanceof Twig_Error_Syntax) {
                 $e->setTemplateFile($file);
             } else {
                 $e = new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e);
             }
             $output = trim(sprintf('%s: %s', get_class($e), $e->getMessage()));
         }
         if (false !== $exception) {
             list($class, ) = explode(':', $exception);
             $this->assertThat(NULL, new PHPUnit_Framework_Constraint_Exception($class));
         }
         $expected = trim($match[3], "\n ");
         if ($expected != $output) {
             echo 'Compiled template that failed:';
             foreach (array_keys($templates) as $name) {
                 echo "Template: {$name}\n";
                 $source = $loader->getSource($name);
                 echo $twig->compile($twig->parse($twig->tokenize($source, $name)));
             }
         }
         $this->assertEquals($expected, $output, $message . ' (in ' . $file . ')');
     }
 }
Exemplo n.º 20
0
 /**
  * Рендерит шаблон
  *
  * @param $name - Имя шаблона
  * @param array $data - Параметры передаваемые в шаблон
  * @param null $path - Путь к папке с шаблонами
  * @throws \Exception
  */
 public function render($name, $data = array(), $path = null)
 {
     try {
         if (is_null($path)) {
             $path = 'Src/views';
         }
         if ($this->moduleName) {
             $path = 'Src/Module/' . $this->moduleName . '/views';
         }
         // Проверка существования шаблона
         if (!is_file($path . '/' . $name)) {
             throw new \Exception('Template "' . $name . '" not found');
         }
         $loader = new \Twig_Loader_Filesystem($path);
         $twig = new \Twig_Environment($loader);
         if (isset($_SESSION)) {
             $twig->addGlobal('session', $_SESSION);
         }
         // Десериализация
         $filter = new \Twig_SimpleFilter('unserialize', 'unserialize');
         $twig->addFilter($filter);
         echo $twig->render($name, $data);
     } catch (\Exception $e) {
         throw new \Exception('Template "' . $name . '" not exists in "' . $path . '"');
     }
 }
Exemplo n.º 21
0
 public function register(Application $app)
 {
     $app['twig.options'] = array();
     $app['twig.form.templates'] = array('form_div_layout.html.twig');
     $app['twig.path'] = array();
     $app['twig.templates'] = array();
     $app['twig'] = $app->share(function ($app) {
         $app['twig.options'] = array_replace(array('charset' => "UTF-8", 'debug' => isset($app['debug']) ? $app['debug'] : false, 'strict_variables' => isset($app['debug']) ? $app['debug'] : false), $app['twig.options']);
         $twig = new \Twig_Environment($app['twig.loader'], $app['twig.options']);
         $twig->addGlobal('app', $app);
         $twig->addExtension(new TwigCoreExtension());
         if (isset($app['debug']) && $app['debug']) {
             $twig->addExtension(new \Twig_Extension_Debug());
         }
         return $twig;
     });
     $app['twig.loader.filesystem'] = $app->share(function ($app) {
         return new \Twig_Loader_Filesystem($app['twig.path']);
     });
     $app['twig.loader.array'] = $app->share(function ($app) {
         return new \Twig_Loader_Array($app['twig.templates']);
     });
     $app['twig.loader.string'] = $app->share(function ($app) {
         return new \Twig_Loader_String();
     });
     $app['twig.loader'] = $app->share(function ($app) {
         return new \Twig_Loader_Chain(array($app['twig.loader.filesystem'], $app['twig.loader.array'], $app['twig.loader.string']));
     });
 }
Exemplo n.º 22
0
 /**
  * Render the template
  * @return string page content
  */
 final function render()
 {
     // Twig Loader
     $twig_loader = new \Twig_Loader_Chain(array(new \Twig_Loader_Filesystem(array(get_stylesheet_directory(), get_template_directory())), new \Twig_Loader_String()));
     // Twig Environment
     $twig = new \Twig_Environment($twig_loader, array('cache' => WP_ENVIRONMENT == 'DEVELOPMENT' ? false : WP_CONTENT_DIR . '/cache/', 'debug' => WP_ENVIRONMENT == 'DEVELOPMENT'));
     // Add Content Function
     $twig->addFunction(new \Twig_SimpleFunction('content', function () {
         return $this->get_content();
     }));
     // Enable {{ dump() }} on local systems
     if (WP_ENVIRONMENT == "DEVELOPMENT") {
         $twig->addExtension(new \Twig_Extension_Debug());
     }
     // Add proxy __call. useful for wp functions like {{ proxy.wp_head() }}
     $twig->addGlobal('proxy', new \Dovetail\Core\TwigProxy());
     // Allow the environment to be altered
     do_action('twig_environment', $twig);
     // Start the view array
     $view = $this->start_view();
     // Get specific properties for this template
     $view = $this->prepare_view($view);
     // Allow global modifications
     do_action('twig_view_vars', $view);
     // Render the string
     ob_start();
     $this->get_template();
     $template = ob_get_contents();
     ob_end_clean();
     echo $twig->render($template, $view);
 }
Exemplo n.º 23
0
 /**
  * Constructor.
  *
  * @param \Twig_Environment           $environment A \Twig_Environment instance
  * @param ContainerInterface          $container   The DI container
  * @param TemplateNameParserInterface $parser      A TemplateNameParserInterface instance
  * @param GlobalVariables             $globals     A GlobalVariables instance
  */
 public function __construct(\Twig_Environment $environment, ContainerInterface $container, TemplateNameParserInterface $parser, GlobalVariables $globals)
 {
     $this->environment = $environment;
     $this->container = $container;
     $this->parser = $parser;
     $environment->addGlobal('app', $globals);
 }
Exemplo n.º 24
0
 public function register(Application $app)
 {
     $app['twig'] = $app->share(function () use($app) {
         $twig = new \Twig_Environment($app['twig.loader'], isset($app['twig.options']) ? $app['twig.options'] : array());
         $twig->addGlobal('app', $app);
         if (isset($app['symfony_bridges'])) {
             if (isset($app['url_generator'])) {
                 $twig->addExtension(new TwigRoutingExtension($app['url_generator']));
             }
             if (isset($app['translator'])) {
                 $twig->addExtension(new TwigTranslationExtension($app['translator']));
             }
             if (isset($app['form.factory'])) {
                 $twig->addExtension(new TwigFormExtension(array('div_layout.html.twig')));
             }
         }
         if (isset($app['twig.configure'])) {
             $app['twig.configure']($twig);
         }
         return $twig;
     });
     $app['twig.loader'] = $app->share(function () use($app) {
         if (isset($app['twig.templates'])) {
             return new \Twig_Loader_Array($app['twig.templates']);
         } else {
             return new \Twig_Loader_Filesystem($app['twig.path']);
         }
     });
     if (isset($app['twig.class_path'])) {
         $app['autoloader']->registerPrefix('Twig_', $app['twig.class_path']);
     }
 }
Exemplo n.º 25
0
 /**
  * @param Twig_Environment $twig
  * @param array            $globals
  */
 public function __construct(\Twig_Environment $twig, array $globals = [])
 {
     foreach ($globals as $key => $value) {
         $twig->addGlobal($key, $value);
     }
     $this->twig = $twig;
 }
 /**
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $host = $request->getHost();
     $baseHost = $this->baseHost;
     $subdomain = str_replace('.' . $baseHost, '', $host);
     //Check subDomain
     $this->checkOldDomains($subdomain);
     //Fix logout bug
     $str = $baseHost . "/login";
     if ($host != $baseHost && strstr($request->getUri(), $str, true)) {
         $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_user_homepage_index')));
     }
     //Fix dashboard error
     if ($this->security_context->getToken() && $this->security_context->isGranted('IS_AUTHENTICATED_REMEMBERED') && $request->get('_route') == 'buddy_system_user_homepage_index') {
         $this->checkSectionAccess();
         $this->activityManager->setUser($this->security_context);
         $this->activityManager->login();
         if ($this->security_context->isGranted('ROLE_ADMIN') || $this->security_context->isGranted('ROLE_SUPER_ADMIN')) {
             $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_sadmin_homepage')));
         } else {
             if ($this->security_context->isGranted('ROLE_BUDDYCOORDINATOR')) {
                 $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_admin_homepage')));
             } else {
                 $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_members_homepage')));
             }
         }
     }
     if ($host == $baseHost) {
         if ($request->get('_route') != null && $request->get('_route') != "buddy_system_choose" && $request->get('_route') != "buddy_system_front_change_language_ajax") {
             $event->setResponse(new RedirectResponse($this->router->generate('buddy_system_choose')));
         }
     } else {
         //Redirection when /en or /fr at the end
         $url = $request->getUri();
         if (substr($url, -3) == "/fr" || substr($url, -3) == "/en") {
             $event->setResponse(new RedirectResponse(substr($url, 0, strlen($url) - 3)));
         }
         //Add Section to local
         if (!$this->sectionManager->getCurrentSection()) {
             /** @var Section $section */
             $section = $this->em->getRepository('BuddySystemMainBundle:Section')->findOneBy(array('subdomain' => $subdomain));
             //Fix error on www
             if (!$section && $subdomain == "www") {
                 header('Location: http://buddysystem.eu');
             }
             if (!$section) {
                 throw new NotFoundHttpException(sprintf('Cannot find section for host "%s", subdomain "%s"', $host, $subdomain));
             }
             if (!array_key_exists('section', $this->twig->getGlobals())) {
                 $this->twig->addGlobal('section', $section);
             }
             $this->sectionManager->setCurrentSection($section);
         }
     }
     if ($this->security_context->getToken() && $this->security_context->getToken()->getUser() && $this->sectionManager->getCurrentSection()) {
         $this->checkSectionAccess();
     }
 }
Exemplo n.º 27
0
 /**
  * Constructor.
  *
  * @param \Twig_Environment           $environment A \Twig_Environment instance
  * @param TemplateNameParserInterface $parser      A TemplateNameParserInterface instance
  * @param GlobalVariables|null        $globals     A GlobalVariables instance or null
  */
 public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, GlobalVariables $globals = null)
 {
     $this->environment = $environment;
     $this->parser = $parser;
     if (null !== $globals) {
         $environment->addGlobal('app', $globals);
     }
 }
Exemplo n.º 28
0
 private static function get_twig()
 {
     Twig_Autoloader::register();
     $twig_loader = new Twig_Loader_Filesystem('app/views');
     $twig_environment = new Twig_Environment($twig_loader);
     $twig_environment->addGlobal('session', $_SESSION);
     return $twig_environment;
 }
 public function view($path, $val = [])
 {
     $loader = new Twig_Loader_Filesystem('../app/views');
     $twig = new Twig_Environment($loader);
     $twig->addGlobal("session", $_SESSION);
     //array_push($val, ['flash'=>'asdfasdfasdf']);
     return $twig->render($path . '.html', $val);
 }
Exemplo n.º 30
0
 /**
  * Renders a view from a template.
  *
  * @param  string $template
  * @param  array  $data
  * @return string
  */
 function view($template, $data = [])
 {
     $loader = new Twig_Loader_Filesystem(base('app/views'));
     $twig = new Twig_Environment($loader);
     // Loads the filters
     $twig->addFilter(new Twig_SimpleFilter('url', 'url'));
     $twig->addFilter(new Twig_SimpleFilter('json', 'json'));
     // Loads the globals
     $twig->addGlobal('request', request());
     $twig->addGlobal('session', session());
     // Loads the functions
     $twig->addFunction(new Twig_SimpleFunction('carbon', 'carbon'));
     $twig->addFunction(new Twig_SimpleFunction('session', 'session'));
     $renderer = new Rougin\Slytherin\Template\Twig\Renderer($twig);
     session(['old' => null, 'validation' => null]);
     return $renderer->render($template, $data, 'twig');
 }