addFilter() public method

public addFilter ( $name, Twig_FilterInterface $filter )
$filter Twig_FilterInterface
 private function maybe_init_twig()
 {
     if (!isset($this->twig)) {
         $loader = new Twig_Loader_Filesystem($this->template_paths);
         $environment_args = array();
         if (WP_DEBUG) {
             $environment_args['debug'] = true;
         }
         $wpml_cache_directory = new WPML_Cache_Directory(new WPML_WP_API());
         $cache_directory = $wpml_cache_directory->get('twig');
         if ($cache_directory) {
             $environment_args['cache'] = $cache_directory;
             $environment_args['auto_reload'] = true;
         }
         $this->twig = new Twig_Environment($loader, $environment_args);
         if (isset($this->custom_functions) && count($this->custom_functions) > 0) {
             foreach ($this->custom_functions as $custom_function) {
                 $this->twig->addFunction($custom_function);
             }
         }
         if (isset($this->custom_filters) && count($this->custom_filters) > 0) {
             foreach ($this->custom_filters as $custom_filter) {
                 $this->twig->addFilter($custom_filter);
             }
         }
     }
 }
 private function init()
 {
     $twig_options = array('cache' => false, 'autoescape' => false, 'strict_variables' => true);
     $loader = new \Twig_Loader_Filesystem(__DIR__ . '/layouts');
     $this->twig = new \Twig_Environment($loader, $twig_options);
     $this->twig->addFilter("removeS", new \Twig_Filter_Function("\\MicroMuffin\\Tools::removeSFromTableName"));
 }
 private function _addFilters(Twig_Environment $environment)
 {
     $transFilter = new Twig_SimpleFilter('trans', array($this, '__callback_trans'));
     $transChoiceFilter = new Twig_SimpleFilter('transChoice', array($this, '__callback_transchoice'));
     $environment->addFilter('trans', $transFilter);
     $environment->addFilter('transChoice', $transChoiceFilter);
 }
 /**
  * @param Configuration  $configuration
  * @param ServiceManager $serviceManager
  */
 public function __construct(Configuration $configuration, ServiceManager $serviceManager)
 {
     if (!$configuration->get('twig', null)) {
         return;
     }
     $cachePath = $configuration->getApplicationPath() . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR;
     $options = [];
     if ($configuration->get('cache.config.enabled', false)) {
         $options['cache'] = $cachePath;
     }
     $paths = $configuration->get('twig.paths', []);
     foreach ($paths as $offset => $path) {
         $paths[$offset] = dirname($configuration->getApplicationPath()) . DIRECTORY_SEPARATOR . 'src' . DIRECTORY_SEPARATOR . $path;
     }
     $loader = new \Twig_Loader_Filesystem($paths);
     $this->twig = new \Twig_Environment($loader, $options + $configuration->get('twig.options', []));
     if (isset($configuration->get('twig.options', [])['debug']) && $configuration->get('twig.options', [])['debug']) {
         $this->twig->addExtension(new \Twig_Extension_Debug());
     }
     foreach ($configuration->get('twig.helpers', []) as $functionName => $helperClass) {
         $func = new \Twig_SimpleFunction($functionName, function () use($helperClass, $serviceManager) {
             $instance = $serviceManager->load($helperClass);
             return call_user_func_array($instance, func_get_args());
         });
         $this->twig->addFunction($func);
     }
     foreach ($configuration->get('twig.filters', []) as $functionName => $helperClass) {
         $func = new \Twig_SimpleFilter($functionName, function () use($helperClass, $serviceManager) {
             $instance = $serviceManager->load($helperClass);
             return call_user_func_array($instance, func_get_args());
         });
         $this->twig->addFilter($func);
     }
 }
 function __construct($content)
 {
     //set the content appropriately
     $this->content = $content;
     $loader = new \Twig_Loader_String();
     $twig = new \Twig_Environment($loader);
     //baseURL & siteURL filter
     $filter = new \Twig_SimpleFilter('*URL', function ($name, $string) {
         $f = $name . '_url';
         return $f($string);
     });
     $twig->addFilter($filter);
     //themeImg filter
     $filter = new \Twig_SimpleFilter('themeImg', function ($string) {
         return theme_img($string);
     });
     $twig->addFilter($filter);
     foreach ($GLOBALS['themeShortcodes'] as $shortcode) {
         $function = new \Twig_SimpleFunction($shortcode['shortcode'], function () use($shortcode) {
             if (is_array($shortcode['method'])) {
                 $class = new $shortcode['method'][0]();
                 return call_user_func_array([$class, $shortcode['method'][1]], func_get_args());
             } else {
                 return call_user_func_array($shortcode['method'], func_get_args());
             }
         });
         $twig->addFunction($function);
     }
     //render the subject and content to a variable
     $this->content = $twig->render($this->content);
 }
 /**
  * @param FileParameter $Location
  * @param bool          $Reload
  *
  * @return IBridgeInterface
  */
 public function loadFile(FileParameter $Location, $Reload = false)
 {
     $this->Instance = new \Twig_Environment(new \Twig_Loader_Filesystem(array(dirname($Location->getFile()))), array('auto_reload' => $Reload, 'autoescape' => false, 'cache' => realpath(__DIR__ . '/TwigTemplate')));
     $this->Instance->addFilter(new \Twig_SimpleFilter('utf8_encode', 'utf8_encode'));
     $this->Instance->addFilter(new \Twig_SimpleFilter('utf8_decode', 'utf8_decode'));
     $this->Template = $this->Instance->loadTemplate(basename($Location->getFile()));
     return $this;
 }
Beispiel #7
0
 /**
  * Renders a Twig template.
  *
  * @param $name
  * @param array $context
  * @return string
  */
 public static function render($name, $context = array())
 {
     if (is_null(static::$twig)) {
         $loader = new \Twig_Loader_Filesystem(dirname(__FILE__) . '/../Resources/views');
         static::$twig = new \Twig_Environment($loader, array());
         static::$twig->addFilter(new \Twig_SimpleFilter('pad', 'str_pad'));
     }
     return static::$twig->render($name, $context);
 }
 /**
  * @param \PDO   $pdo
  * @param string $sSchema
  * @param string $sSaveDir
  * @param string $sNamespace
  */
 public function __construct(\PDO $pdo, $sSchema, $sSaveDir, $sNamespace)
 {
     $this->pdo = $pdo;
     $this->schema = $sSchema;
     $this->modelSaveDir = $sSaveDir;
     $this->modelNamespace = $sNamespace;
     $twig_options = array('cache' => false, 'autoescape' => false, 'strict_variables' => true);
     $loader = new \Twig_Loader_Filesystem(__DIR__ . '/../layout');
     $this->twig = new \Twig_Environment($loader, $twig_options);
     $this->twig->addFilter("removeS", new \Twig_Filter_Function("\\Mrblackus\\LaravelStoredProcedures\\Tools::removeSFromTableName"));
 }
Beispiel #9
0
 /**
  * @return \Twig_Environment
  */
 private function getTwigInstance()
 {
     $twigLoader = new \Twig_Loader_Filesystem([__DIR__ . '/Pages']);
     $twigEnvironment = new \Twig_Environment($twigLoader);
     $twigEnvironment->addExtension(new \Twig_Extension_Debug());
     $dateFormatter = new \IntlDateFormatter(null, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE);
     $dateTimeFormatter = new \IntlDateFormatter(null, \IntlDateFormatter::MEDIUM, \IntlDateFormatter::SHORT);
     $twigEnvironment->addFilter($this->getIntlDateFilter('formatDate', $dateFormatter));
     $twigEnvironment->addFilter($this->getIntlDateFilter('formatDateTime', $dateTimeFormatter));
     return $twigEnvironment;
 }
Beispiel #10
0
 public function render($app, $method = null, array $vars = array())
 {
     // Detect Page Method
     if ($method === null) {
         $uri_full = 'http://' . $app->request->server->get('HTTP_HOST') . $app->request->server->get('REQUEST_URI');
         $uri_path = parse_url($uri_full, PHP_URL_PATH);
         $uri_parts = explode('/', $uri_path);
         array_shift($uri_parts);
         $method = !empty($uri_parts[0]) ? $uri_parts[0] : 'dashboard';
     } else {
         $uri_parts = array('error');
     }
     // Check if method exists
     $class = 'Controller\\' . ucfirst($method);
     if (!class_exists($class)) {
         $method = 'error';
         header('HTTP/1.1 404 Not Found');
         $class = 'Controller\\Error';
     }
     // Initialize class
     $page = new $class($app);
     $page->uri = $uri_parts;
     $page->var = $vars;
     if ($page->view === null) {
         $page->view = $method;
     }
     $page->controller = $method;
     $page->config = $app->config;
     $page->before();
     $response = $page->{'req_' . $app->request->getMethod()}();
     $page->after();
     $page->template = 'Page/' . ucfirst($page->view) . '.twig';
     // JSON Responses Don't need Twig
     if ($response instanceof JsonResponse) {
         return $response->send();
     }
     // Sort out variables
     $twig_variables = $page->var;
     $twig_variables['page'] = $page;
     $twig_variables['app'] = $app;
     $twig_variables['auth'] = $app->auth;
     $twig_variables['user'] = $app->auth->user;
     // Twig Setup
     $loader = new \Twig_Loader_Filesystem(dirname(dirname(__DIR__)) . '/app/View');
     $twig = new \Twig_Environment($loader, array());
     $twig->addFilter(new \Twig_SimpleFilter('normalize_bytes', function ($bytes, $precision = 2, $html = false) {
         return \Utils::normalize_bytes($bytes, $precision, $html);
     }, array('is_safe' => array('html'))));
     $twig->addFilter(new \Twig_SimpleFilter('json', function ($string) {
         return json_encode($string, JSON_PRETTY_PRINT);
     }));
     echo $twig->render('Layout/Default.twig', $twig_variables);
 }
 /**
  * Apply Twig to given template
  * 
  * @param  string $html File path or HTML string.
  * @param  array  $vars optional variables for Twig context
  * @return string       rendered template string
  */
 public static function apply_to_html($html, $vars = array())
 {
     // file loader for internal use
     $file_loader = new \Twig_Loader_Filesystem();
     $file_loader->addPath(implode(DIRECTORY_SEPARATOR, array(\Podlove\PLUGIN_DIR, 'templates')), 'core');
     // other modules can register their own template directories/namespaces
     $file_loader = apply_filters('podlove_twig_file_loader', $file_loader);
     // database loader for user templates
     $db_loader = new TwigLoaderPodloveDatabase();
     $loaders = array($file_loader, $db_loader);
     $loaders = apply_filters('podlove_twig_loaders', $loaders);
     $loader = new \Twig_Loader_Chain($loaders);
     $twig = new \Twig_Environment($loader, array('autoescape' => false));
     $twig->addExtension(new \Twig_Extensions_Extension_I18n());
     $twig->addExtension(new \Twig_Extensions_Extension_Date());
     $formatBytesFilter = new \Twig_SimpleFilter('formatBytes', function ($string) {
         return \Podlove\format_bytes($string, 0);
     });
     $padLeftFilter = new \Twig_SimpleFilter('padLeft', function ($string, $padChar, $length) {
         while (strlen($string) < $length) {
             $string = $padChar . $string;
         }
         return $string;
     });
     $twig->addFilter($formatBytesFilter);
     $twig->addFilter($padLeftFilter);
     // add functions
     foreach (self::$template_tags as $tag) {
         $func = new \Twig_SimpleFunction($tag, function () use($tag) {
             return $tag();
         });
         $twig->addFunction($func);
     }
     $context = ['option' => $vars];
     // add podcast to global context
     $context = array_merge($context, ['podcast' => new Podcast(Model\Podcast::get())]);
     // Apply filters to twig templates
     $context = apply_filters('podlove_templates_global_context', $context);
     // add podcast to global context if we are in an episode
     if ($episode = Model\Episode::find_one_by_property('post_id', get_the_ID())) {
         $context = array_merge($context, array('episode' => new Episode($episode)));
     }
     try {
         return $twig->render($html, $context);
     } catch (\Twig_Error $e) {
         $message = $e->getRawMessage();
         $line = $e->getTemplateLine();
         $template = $e->getTemplateFile();
         \Podlove\Log::get()->addError($message, ['type' => 'twig', 'line' => $line, 'template' => $template]);
     }
     return "";
 }
Beispiel #12
0
 public function getTests()
 {
     $environment = new Twig_Environment();
     $environment->addFilter(new Twig_SimpleFilter('bar', 'bar', array('needs_environment' => true)));
     $environment->addFilter(new Twig_SimpleFilter('barbar', 'twig_tests_filter_barbar', array('needs_context' => true, 'is_variadic' => true)));
     $tests = array();
     $expr = new Twig_Node_Expression_Constant('foo', 1);
     $node = $this->createFilter($expr, 'upper');
     $node = $this->createFilter($node, 'number_format', array(new Twig_Node_Expression_Constant(2, 1), new Twig_Node_Expression_Constant('.', 1), new Twig_Node_Expression_Constant(',', 1)));
     if (function_exists('mb_get_info')) {
         $tests[] = array($node, 'twig_number_format_filter($this->env, twig_upper_filter($this->env, "foo"), 2, ".", ",")');
     } else {
         $tests[] = array($node, 'twig_number_format_filter($this->env, strtoupper("foo"), 2, ".", ",")');
     }
     // named arguments
     $date = new Twig_Node_Expression_Constant(0, 1);
     $node = $this->createFilter($date, 'date', array('timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), 'format' => new Twig_Node_Expression_Constant('d/m/Y H:i:s P', 1)));
     $tests[] = array($node, 'twig_date_format_filter($this->env, 0, "d/m/Y H:i:s P", "America/Chicago")');
     // skip an optional argument
     $date = new Twig_Node_Expression_Constant(0, 1);
     $node = $this->createFilter($date, 'date', array('timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1)));
     $tests[] = array($node, 'twig_date_format_filter($this->env, 0, null, "America/Chicago")');
     // underscores vs camelCase for named arguments
     $string = new Twig_Node_Expression_Constant('abc', 1);
     $node = $this->createFilter($string, 'reverse', array('preserve_keys' => new Twig_Node_Expression_Constant(true, 1)));
     $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)');
     $node = $this->createFilter($string, 'reverse', array('preserveKeys' => new Twig_Node_Expression_Constant(true, 1)));
     $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)');
     // filter as an anonymous function
     if (PHP_VERSION_ID >= 50300) {
         $node = $this->createFilter(new Twig_Node_Expression_Constant('foo', 1), 'anonymous');
         $tests[] = array($node, 'call_user_func_array($this->env->getFilter(\'anonymous\')->getCallable(), array("foo"))');
     }
     // needs environment
     $node = $this->createFilter($string, 'bar');
     $tests[] = array($node, 'bar($this->env, "abc")', $environment);
     $node = $this->createFilter($string, 'bar', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'bar($this->env, "abc", "bar")', $environment);
     // arbitrary named arguments
     $node = $this->createFilter($string, 'barbar');
     $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc")', $environment);
     $node = $this->createFilter($string, 'barbar', array('foo' => new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, null, array("foo" => "bar"))', $environment);
     $node = $this->createFilter($string, 'barbar', array('arg2' => new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, "bar")', $environment);
     $node = $this->createFilter($string, 'barbar', array(new Twig_Node_Expression_Constant('1', 1), new Twig_Node_Expression_Constant('2', 1), new Twig_Node_Expression_Constant('3', 1), 'foo' => new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", "1", "2", array(0 => "3", "foo" => "bar"))', $environment);
     return $tests;
 }
Beispiel #13
0
 protected function initialize(InputInterface $input, OutputInterface $output)
 {
     $this->settings = $this->getApplication()->getSettings();
     $loader = new \Twig_Loader_Filesystem($this->settings->getPackageBaseDir() . '/config-dist');
     $this->twig = new \Twig_Environment($loader);
     $filter = new \Twig_SimpleFilter('bool', function ($value) {
         if ($value) {
             return 'true';
         } else {
             return 'false';
         }
     });
     $this->twig->addFilter($filter);
     $this->parseComposerConfig();
 }
 /**
  * Load filters for the Twig PatternEngine
  * @param  {Instance}       an instance of the twig engine
  *
  * @return {Instance}       an instance of the twig engine
  */
 public static function loadFilters(\Twig_Environment $instance)
 {
     // load defaults
     $filterDir = Config::getOption("sourceDir") . DIRECTORY_SEPARATOR . "_twig-components/filters";
     $filterExt = Config::getOption("twigFilterExt");
     $filterExt = $filterExt ? $filterExt : "filter.php";
     if (is_dir($filterDir)) {
         // loop through the filter dir...
         $finder = new Finder();
         $finder->files()->name("*\\." . $filterExt)->in($filterDir);
         $finder->sortByName();
         foreach ($finder as $file) {
             // see if the file should be ignored or not
             $baseName = $file->getBasename();
             if ($baseName[0] != "_") {
                 include $file->getPathname();
                 // $filter should be defined in the included file
                 if (isset($filter)) {
                     $instance->addFilter($filter);
                     unset($filter);
                 }
             }
         }
     } else {
         self::dirNotExist($filterDir);
     }
     $instance->addExtension(new Twig_Extensions_Extension_Intl());
     return $instance;
 }
Beispiel #15
0
 public function render($echo = false)
 {
     // Load template directories.
     $loader = new \Twig_Loader_Filesystem();
     $loader->addPath('templates');
     // Set up Twig.
     $twig = new \Twig_Environment($loader, array('debug' => true, 'strct_variables' => true));
     $twig->addExtension(new \Twig_Extension_Debug());
     // Mardown support.
     $twig->addFilter(new \Twig_SimpleFilter('markdown', function ($text) {
         $parsedown = new \Parsedown();
         return $parsedown->text($text);
     }));
     // DB queries.
     $twig->addFunction(new \Twig_SimpleFunction('db_queries', function () {
         return Db::getQueries();
     }));
     // Render.
     $string = $twig->render($this->template, $this->data);
     if ($echo) {
         echo $string;
     } else {
         return $string;
     }
 }
Beispiel #16
0
 public function render()
 {
     // Merge with Global Data Static array
     $this->data = array_merge(self::$global_data, $this->data);
     // Inject "fw" object
     $this->data["fw"] = new \Fw\Twig\Extend();
     // Determine Template Path
     if (!($template_path = \Fw\Find::in("views", $this->template_file))) {
         throw new \Exception("Template File (" . $this->template_file . ") not found. Looked in " . \Fw\Debug::get());
     }
     $template_path_info = pathinfo($template_path);
     // Init Twig Loader. Search paths are the Fw00t view paths.
     $loader = new \Twig_Loader_Filesystem(array_merge(array($template_path_info["dirname"]), \Fw\Find::get_paths("views")));
     // Init Twig Renderer Environment
     if (\Fw\Config::get("env") == \Fw\Config::PRODUCTION) {
         $twig = new \Twig_Environment($loader, array('cache' => $this->cache_dir));
     } else {
         $twig = new \Twig_Environment($loader, array());
     }
     foreach (self::$filters as $filter) {
         $twig->addFilter($filter);
     }
     // Commence Twigging
     $template = $twig->loadTemplate($template_path_info["basename"]);
     return $template->render($this->data);
 }
Beispiel #17
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 . '"');
     }
 }
Beispiel #18
0
 public function render($route, $log = null)
 {
     $template_path = $route->join('/') . '/' . $this->context->template . '.tpl';
     $template_base_path = APP_ROOT . '/Views';
     $cache = false;
     if (isset(\Config\Base::$caching) && \Config\Base::$caching == true) {
         $cache = \Config\Base::$caching['twig'] ? APP_ROOT . '/cache' : false;
     }
     $loader = new \Bacon\Loader($template_base_path, $template_path);
     $twig = new \Twig_Environment($loader, ['cache' => $cache, 'auto_reload' => true]);
     if (!empty($this->context->template_base_paths)) {
         foreach ($this->context->template_base_paths as $path) {
             $loader->addPath($path);
         }
     }
     if (!empty($this->context->filters)) {
         foreach ($this->context->filters->getArrayCopy() as $name => $function) {
             $filter_function = new \Twig_Filter_Function($function, ['is_safe' => ['html']]);
             $twig->addFilter($name, $filter_function);
         }
     }
     if (!empty($this->context->locale)) {
         $locale = $this->context->locale;
         $translator = new Translator($locale, new MessageSelector());
         $translator->addLoader('po', new PoFileLoader());
         $translator->addResource('po', APP_ROOT . '/locales/' . $locale . '/' . $this->context->locale_file . '.po', $locale);
         $twig->addExtension(new \Symfony\Bridge\Twig\Extension\TranslationExtension($translator));
     }
     echo $twig->render($template_path, $this->context->getArrayCopy());
 }
Beispiel #19
0
 /**
  * Configure report generator.
  *
  * @param string $reportDir Report output directory
  * @param array $altTemplatePaths Paths to alternative templates.
  */
 public function __construct($reportDir, array $altTemplatePaths = [])
 {
     array_push($altTemplatePaths, __DIR__ . DIRECTORY_SEPARATOR . 'Templates');
     $loader = new \Twig_Loader_Filesystem($altTemplatePaths);
     $this->twig = new \Twig_Environment($loader);
     $this->twig->addFunction(new \Twig_SimpleFunction('explode', 'explode'));
     $this->twig->addFunction(new \Twig_SimpleFunction('levelUp', [$this, 'levelUp']));
     $this->twig->addFunction(new \Twig_SimpleFunction('getTestPercent', [$this, 'getTestPercent']));
     $this->twig->addFilter(new \Twig_SimpleFilter('getPathByNamespace', [$this, 'getPathByNamespace']));
     $this->fs = new Filesystem();
     if (!$this->fs->exists($reportDir)) {
         $this->fs->mkdir($reportDir);
     }
     $this->outputDir = realpath($reportDir);
     $this->statistics = new ClassStatistics();
 }
Beispiel #20
0
 public function render()
 {
     delete_transient($this->transient_notices);
     $loader = new \Twig_Loader_Filesystem($this->paths);
     $twig = new \Twig_Environment($loader);
     // Add the admin_url() function.
     $twig->addFunction('admin_url', new \Twig_SimpleFunction('admin_url', 'admin_url'));
     // Add titlecase filter.
     $titlecase_filter = new \Twig_SimpleFilter('titlecase', '\\WordPress\\Tabulate\\Text::titlecase');
     $twig->addFilter($titlecase_filter);
     // Add date and time filters.
     $date_filter = new \Twig_SimpleFilter('wp_date_format', '\\WordPress\\Tabulate\\Text::wp_date_format');
     $twig->addFilter($date_filter);
     $time_filter = new \Twig_SimpleFilter('wp_time_format', '\\WordPress\\Tabulate\\Text::wp_time_format');
     $twig->addFilter($time_filter);
     // Add strtolower filter.
     $strtolower_filter = new \Twig_SimpleFilter('strtolower', function ($str) {
         if (is_array($str)) {
             return array_map('strtolower', $str);
         } else {
             return strtolower($str);
         }
     });
     $twig->addFilter($strtolower_filter);
     // Enable debugging.
     if (WP_DEBUG) {
         $twig->enableDebug();
         $twig->addExtension(new \Twig_Extension_Debug());
     }
     // Render the template.
     $template = $twig->loadTemplate($this->templateName);
     return $template->render($this->data);
 }
Beispiel #21
0
 protected function getEnvironment()
 {
     $env = new Twig_Environment(new Twig_Loader_Array(array()));
     $env->addFilter(new Twig_Filter('anonymous', function () {
     }));
     return $env;
 }
Beispiel #22
0
 /**
  * Adds the WP-specific filters and functions to the twig environment
  * @param \Twig_Environment $twig_Environment
  */
 private static function extendTwig(\Twig_Environment $twig_Environment)
 {
     $twig_Environment->addFilter(new \Twig_SimpleFilter('__', function ($text, $domain = 'default') {
         return __($text, $domain);
     }));
     $twig_Environment->addExtension(new SlugifyExtension(Slugify::create()));
 }
Beispiel #23
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;
 }
Beispiel #24
0
function dwInitTwigEnvironment(Twig_Environment $twig)
{
    $twig->setCache(ROOT_PATH . '/tmp/twig');
    $twig->enableAutoReload();
    $twig->addExtension(new Twig_I18n_Extension());
    $twig->addFilter(new Twig_SimpleFilter('purify', function ($dirty) {
        return dwGetHTMLPurifier()->purify($dirty);
    }));
    $twig->addFilter(new Twig_SimpleFilter('json', function ($arr) {
        $mask = 0;
        if (!empty($opts)) {
            if (!empty($opts['pretty'])) {
                $mask = $mask | JSON_PRETTY_PRINT;
            }
        }
        return json_encode($arr, $mask);
    }));
    $twig->addFilter(new Twig_SimpleFilter('css', function ($arr) {
        $css = '';
        foreach ($arr as $prop => $val) {
            $css .= $prop . ':' . $val . ';';
        }
        return $css;
    }));
    $twig->addFunction(new Twig_SimpleFunction('hook', function () {
        call_user_func_array(array(DatawrapperHooks::getInstance(), 'execute'), func_get_args());
    }));
    $twig->addFunction(new Twig_SimpleFunction('has_hook', function ($hook) {
        return DatawrapperHooks::getInstance()->hookRegistered($hook);
    }));
    $twig->addFunction(new Twig_SimpleFunction('has_plugin', function ($plugin) {
        return DatawrapperPluginManager::loaded($plugin);
    }));
    $twig->addFilter(new Twig_SimpleFilter('lettering', function ($text) {
        $out = '';
        foreach (str_split($text) as $i => $char) {
            $out .= '<span class="char' . $i . '">' . $char . '</span>';
        }
        return $out;
    }, array('is_safe' => array('html'))));
    \Moment\Moment::setLocale(str_replace('-', '_', DatawrapperSession::getLanguage()));
    $twig->addFilter(new Twig_SimpleFilter('reltime', function ($time) {
        // return $time;
        return (new \Moment\Moment($time))->fromNow()->getRelative();
    }));
    return $twig;
}
Beispiel #25
0
 /**
  * Add a filter to Twig
  *
  * @param string $name - Name to access n Twig
  * @param callable $func - function to apply
  * @return Lens
  */
 public function filter(string $name, $func = null) : self
 {
     if (empty($func)) {
         $func = '\\Airship\\LensFunctions\\' . $name;
     }
     $this->twigEnv->addFilter(new \Twig_SimpleFilter($name, $func));
     return $this;
 }
 /**
  * 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');
 }
Beispiel #27
0
function load_twig()
{
    global $twig, $config;
    require 'lib/Twig/Autoloader.php';
    Twig_Autoloader::register();
    Twig_Autoloader::autoload('Twig_Extensions_Node_Trans');
    Twig_Autoloader::autoload('Twig_Extensions_TokenParser_Trans');
    Twig_Autoloader::autoload('Twig_Extensions_Extension_I18n');
    Twig_Autoloader::autoload('Twig_Extensions_Extension_Tinyboard');
    $loader = new Twig_Loader_Filesystem($config['dir']['template']);
    $loader->setPaths($config['dir']['template']);
    $twig = new Twig_Environment($loader, array('autoescape' => false, 'cache' => (is_writable('templates') || is_dir('templates/cache') && is_writable('templates/cache')) && $config['twig_cache'] ? "{$config['dir']['template']}/cache" : false, 'debug' => $config['debug']));
    $twig->addExtension(new Twig_Extensions_Extension_Tinyboard());
    $twig->addExtension(new Twig_Extensions_Extension_I18n());
    $twig->addFilter(new Twig_SimpleFilter('hex2bin', 'hex2bin'));
    $twig->addFilter(new Twig_SimpleFilter('base64_encode', 'base64_encode'));
}
Beispiel #28
0
 function __construct()
 {
     parent::__construct();
     $this['config'] = function ($c) {
         return new Config(__DIR__ . "/../config.ini");
     };
     $this['db'] = function ($c) {
         $db = new \Services\MySQL\MySqlConnection($c->config->mysql->host, $c->config->mysql->username, $c->config->mysql->password, $c->config->mysql->db_name);
         $db->setTimeZone("+00:00");
         return $db;
     };
     $this['eb'] = function ($c) {
         return new \Services\Eventbrite\Eventbrite(array('app_key' => $c->config->eventbrite->appkey, 'user_key' => $c->config->eventbrite->userkey));
     };
     $this['mailchimp'] = function ($c) {
         return new \Services\Mailchimp\MCAPI($c->config->mailchimp->api_key);
     };
     $this['view'] = function ($c) {
         $loader = new Twig_Loader_Filesystem(realpath(__DIR__ . '/../../app/views'));
         $twig = new Twig_Environment($loader, array('cache' => realpath(__DIR__ . '/../../' . $c->config->view->cache_path), 'debug' => true));
         $twig->addFilter(new Twig_SimpleFilter('slugify', function ($string) {
             return strtolower(str_replace(' ', '-', $string));
         }));
         $twig->addFilter(new Twig_SimpleFilter('tourl', function ($string) {
             return rawurlencode(str_replace('\\n', ',', $string));
         }));
         $twig->addFilter(new Twig_SimpleFilter('timeago', function ($date) {
             return Carbon::instance($date)->diffForHumans();
         }));
         $twig->addGlobal('server', array('request_uri' => $_SERVER['REQUEST_URI']));
         $twig->addGlobal('layout', array('allevents' => $c->db->queryAllRows('(SELECT * FROM events WHERE end_time < NOW()) UNION (SELECT * FROM events WHERE end_time > NOW() ORDER BY end_time LIMIT 1) ORDER BY start_time DESC')));
         $twig->addExtension(new Twig_Extension_Debug());
         return $twig;
     };
     $this['auth'] = function ($c) {
         if (!session_id()) {
             session_start();
         }
         $host = $_SERVER['HTTP_HOST'];
         return new \Services\GoogleAuth\GoogleAuth($_SESSION, $c->config->google->client_id, $c->config->google->secret, array('canceldest' => 'http://edgeconf.com/', 'callback' => $c->config->google->callback));
     };
     $this['sentry'] = function ($c) {
         return new Raven_Client($c->config->sentry->dsn, array('tags' => array('php_version' => phpversion())));
     };
 }
Beispiel #29
0
 /**
  * Registers a filters repository
  *
  * @param string $classname
  * @throws \ErrorException
  */
 public function registerFilter($classname)
 {
     if (!class_exists($classname)) {
         throw new \ErrorException("Required class does not exist.");
     }
     $filter_names = get_class_methods($classname);
     foreach ($filter_names as $filter_name) {
         $filter = new \Twig_SimpleFilter($filter_name, array($classname, $filter_name), array('needs_environment' => true));
         $this->environment->addFilter($filter);
     }
 }
Beispiel #30
0
 /**
  * Registers the template filters.
  */
 private function registerFilters()
 {
     $filters = config('app.render_filters', []);
     foreach ($filters as $filter) {
         $filter = app($filter);
         if ($filter instanceof FilterContract) {
             $this->twigEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(), $filter->getFilter()));
             $this->twigStringEnvironment->addFilter(new \Twig_SimpleFilter($filter->getName(), $filter->getFilter()));
         }
     }
 }