addFunction() public method

Registers a Function.
public addFunction ( string $name, Twig_FunctionInterface $function )
$name string The function name
$function Twig_FunctionInterface A Twig_FunctionInterface instance
 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);
             }
         }
     }
 }
 public function getTests()
 {
     $environment = new Twig_Environment();
     $environment->addFunction('foo', new Twig_Function_Function('foo', array()));
     $environment->addFunction('bar', new Twig_Function_Function('bar', array('needs_environment' => true)));
     $environment->addFunction('foofoo', new Twig_Function_Function('foofoo', array('needs_context' => true)));
     $environment->addFunction('foobar', new Twig_Function_Function('foobar', array('needs_environment' => true, 'needs_context' => true)));
     $tests = array();
     $node = $this->createFunction('foo');
     $tests[] = array($node, 'foo()', $environment);
     $node = $this->createFunction('foo', array(new Twig_Node_Expression_Constant('bar', 0), new Twig_Node_Expression_Constant('foobar', 0)));
     $tests[] = array($node, 'foo("bar", "foobar")', $environment);
     $node = $this->createFunction('bar');
     $tests[] = array($node, 'bar($this->env)', $environment);
     $node = $this->createFunction('bar', array(new Twig_Node_Expression_Constant('bar', 0)));
     $tests[] = array($node, 'bar($this->env, "bar")', $environment);
     $node = $this->createFunction('foofoo');
     $tests[] = array($node, 'foofoo($context)', $environment);
     $node = $this->createFunction('foofoo', array(new Twig_Node_Expression_Constant('bar', 0)));
     $tests[] = array($node, 'foofoo($context, "bar")', $environment);
     $node = $this->createFunction('foobar');
     $tests[] = array($node, 'foobar($this->env, $context)', $environment);
     $node = $this->createFunction('foobar', array(new Twig_Node_Expression_Constant('bar', 0)));
     $tests[] = array($node, 'foobar($this->env, $context, "bar")', $environment);
     return $tests;
 }
Example #3
0
 public function getTests()
 {
     $environment = new Twig_Environment();
     $environment->addFunction('foo', new Twig_Function_Function('foo', array()));
     $environment->addFunction('bar', new Twig_Function_Function('bar', array('needs_environment' => true)));
     $environment->addFunction('foofoo', new Twig_Function_Function('foofoo', array('needs_context' => true)));
     $environment->addFunction('foobar', new Twig_Function_Function('foobar', array('needs_environment' => true, 'needs_context' => true)));
     $tests = array();
     $node = $this->createFunction('foo');
     $tests[] = array($node, 'foo()', $environment);
     $node = $this->createFunction('foo', array(new Twig_Node_Expression_Constant('bar', 1), new Twig_Node_Expression_Constant('foobar', 1)));
     $tests[] = array($node, 'foo("bar", "foobar")', $environment);
     $node = $this->createFunction('bar');
     $tests[] = array($node, 'bar($this->env)', $environment);
     $node = $this->createFunction('bar', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'bar($this->env, "bar")', $environment);
     $node = $this->createFunction('foofoo');
     $tests[] = array($node, 'foofoo($context)', $environment);
     $node = $this->createFunction('foofoo', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'foofoo($context, "bar")', $environment);
     $node = $this->createFunction('foobar');
     $tests[] = array($node, 'foobar($this->env, $context)', $environment);
     $node = $this->createFunction('foobar', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'foobar($this->env, $context, "bar")', $environment);
     // named arguments
     $node = $this->createFunction('date', array('timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), 'date' => new Twig_Node_Expression_Constant(0, 1)));
     $tests[] = array($node, 'twig_date_converter($this->env, 0, "America/Chicago")');
     return $tests;
 }
Example #4
0
 public function init()
 {
     $view_dir = [__DIR__ . '/../Views', __DIR__ . '/../Templates'];
     $twigConfig = [];
     if ($this->config['twig']['cache']) {
         $twigConfig["cache"] = $this->app['cache']['twig'];
     }
     $twigConfig["debug"] = $this->config['twig']['debug'];
     $loader = new \Twig_Loader_Filesystem($view_dir);
     foreach ($view_dir as $d) {
         $loader->addPath($d, 'Meister');
     }
     foreach ($this->config['modules'] as $app) {
         if (file_exists($this->app['Modules'] . $app . '/Views')) {
             $loader->addPath($this->app['Modules'] . $app . '/Views', $app);
         }
         if (file_exists($this->app['Modules'] . $app . '/Templates')) {
             $loader->addPath($this->app['Modules'] . $app . '/Templates', $app);
         }
     }
     $this->twig = new \Twig_Environment($loader, $twigConfig);
     $this->twig->addExtension(new \Twig_Extensions_Extension_I18n());
     /**
      * Verifica permissões para exibir determinada coisa
      */
     $function = new \Twig_SimpleFunction('permission', function ($rule) {
         return $this->app['auth']->checkRules($rule);
     });
     $this->twig->addFunction($function);
 }
Example #5
0
 public function getTests()
 {
     $environment = new Twig_Environment();
     $environment->addFunction('foo', new Twig_Function_Function('foo', array()));
     $environment->addFunction('bar', new Twig_Function_Function('bar', array('needs_environment' => true)));
     $environment->addFunction('foofoo', new Twig_Function_Function('foofoo', array('needs_context' => true)));
     $environment->addFunction('foobar', new Twig_Function_Function('foobar', array('needs_environment' => true, 'needs_context' => true)));
     $tests = array();
     $node = $this->createFunction('foo');
     $tests[] = array($node, 'foo()', $environment);
     $node = $this->createFunction('foo', array(new Twig_Node_Expression_Constant('bar', 1), new Twig_Node_Expression_Constant('foobar', 1)));
     $tests[] = array($node, 'foo("bar", "foobar")', $environment);
     $node = $this->createFunction('bar');
     $tests[] = array($node, 'bar($this->env)', $environment);
     $node = $this->createFunction('bar', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'bar($this->env, "bar")', $environment);
     $node = $this->createFunction('foofoo');
     $tests[] = array($node, 'foofoo($context)', $environment);
     $node = $this->createFunction('foofoo', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'foofoo($context, "bar")', $environment);
     $node = $this->createFunction('foobar');
     $tests[] = array($node, 'foobar($this->env, $context)', $environment);
     $node = $this->createFunction('foobar', array(new Twig_Node_Expression_Constant('bar', 1)));
     $tests[] = array($node, 'foobar($this->env, $context, "bar")', $environment);
     // named arguments
     $node = $this->createFunction('date', array('timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), 'date' => new Twig_Node_Expression_Constant(0, 1)));
     $tests[] = array($node, 'twig_date_converter($this->env, 0, "America/Chicago")');
     // function as an anonymous function
     if (version_compare(phpversion(), '5.3.0', '>=')) {
         $node = $this->createFunction('anonymous', array(new Twig_Node_Expression_Constant('foo', 1)));
         $tests[] = array($node, 'call_user_func_array($this->env->getFunction(\'anonymous\')->getCallable(), array("foo"))');
     }
     return $tests;
 }
Example #6
0
function awsautoses_twig()
{
    $cache = WP_CONTENT_DIR . '/cache/aws-auto-ses/tplcache';
    if (!is_dir($cache)) {
        if (!mkdir($cache, 0755, true)) {
            $cache = false;
        }
    } else {
        if (is_writable($cache)) {
            $cache = false;
        }
    }
    $loader = new Twig_Loader_Filesystem(__DIR__ . '/tpl');
    $twig = new Twig_Environment($loader, array('cache' => $cache));
    $twig->addExtension(new Twig_Extension_Escaper('html'));
    foreach (array('__') as $fn) {
        $twig->addFunction(new Twig_SimpleFunction($fn, function () use($fn) {
            $args = func_get_args();
            return call_user_func_array($fn, $args);
        }));
    }
    foreach (array('settings_fields', 'do_settings_sections', 'submit_button') as $fn) {
        $twig->addFunction(new Twig_SimpleFunction($fn, function () use($fn) {
            $args = func_get_args();
            ob_start();
            call_user_func_array($fn, $args);
            return ob_get_clean();
        }));
    }
    return $twig;
}
Example #7
0
 /**
  * @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);
     }
 }
Example #8
0
 /**
  * Registers a function repository
  *
  * @param string $classname
  * @throws \ErrorException
  */
 public function registerFunctions($classname)
 {
     if (!class_exists($classname)) {
         throw new \ErrorException("Required class does not exist");
     }
     $function_names = get_class_methods($classname);
     foreach ($function_names as $function_name) {
         $func = new \Twig_SimpleFunction($function_name, array($classname, $function_name), array('needs_environment' => true));
         $this->environment->addFunction($func);
     }
 }
Example #9
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'))));
    $loc = DatawrapperSession::getLanguage();
    if ($loc == 'en') {
        $loc = 'en-US';
    }
    \Moment\Moment::setLocale(str_replace('-', '_', $loc));
    $twig->addFilter(new Twig_SimpleFilter('reltime', function ($time) {
        // return $time;
        return (new \Moment\Moment($time))->fromNow()->getRelative();
    }));
    if (!empty($GLOBALS['dw_config']['debug'])) {
        $twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));
    }
    return $twig;
}
Example #10
0
 /**
  * Constructor
  *
  * @param ObjectConfig $config   An optional ObjectConfig object with configuration options
  */
 public function __construct(ObjectConfig $config)
 {
     parent::__construct($config);
     //Reset the stack
     $this->_stack = array();
     $this->_twig = new \Twig_Environment($this, array('cache' => $this->_cache ? $this->_cache_path : false, 'auto_reload' => $this->_cache_reload, 'debug' => $config->debug, 'autoescape' => $config->autoescape, 'strict_variables' => $config->strict_variables, 'optimizations' => $config->optimizations));
     //Register functions in twig
     foreach ($this->getFunctions() as $name => $callable) {
         $function = new \Twig_SimpleFunction($name, $callable);
         $this->_twig->addFunction($function);
     }
 }
Example #11
0
 /**
  * Inits the Twig environment
  *
  * Response constructor.
  */
 public function __construct()
 {
     $PATHS = Config::get('path');
     $this->loader = new \Twig_Loader_Filesystem(ROOT . $PATHS->templates);
     $this->environment = new \Twig_Environment($this->loader, array('cache' => ROOT . $PATHS->twig_cache, 'debug' => Config::get('debug')));
     // register new functions
     $function_names = get_class_methods("\\Got\\Core\\TwigExtensions\\Functions");
     foreach ($function_names as $func_name) {
         $func = new \Twig_SimpleFunction($func_name, array("\\Got\\Core\\TwigExtensions\\Functions", $func_name));
         $this->environment->addFunction($func);
     }
 }
Example #12
0
 protected function _compile()
 {
     $env = new \Twig_Environment(new \Twig_Loader_Filesystem(SOURCE_PATH), array('autoescape' => false, 'cache' => TMP_PATH . 'twig', 'debug' => true, 'base_template_class' => 'eBuildy\\Templating\\TwigBaseTemplate'));
     $env->registerUndefinedFunctionCallback(array($this, "undefinedFunctionCallback"));
     $env->addGlobal('__template_name', basename($this->templatePath));
     foreach ($this->exposedMethod as $methodName => $method) {
         if (isset($method['service'])) {
             $env->addFunction($methodName, new \Twig_SimpleFunction($methodName, '$this->container->' . \eBuildy\Helper\ResolverHelper::resolveServiceMethodName($method['service']) . '()->' . $method['method']));
         } else {
             $env->addFunction($methodName, new \Twig_SimpleFunction($methodName, '$this->' . $methodName));
         }
     }
     $template = $env->loadTemplate(str_replace(SOURCE_PATH, '', $this->templatePath));
     return $template;
 }
Example #13
0
 /**
  * Adds the Blocklyduino-specific assets our application needs
  * @param \Twig_Environment $twig The Twig environment to add the asset paths to
  * @param Blocklyduino $app The application
  */
 static function addBlocklyduinoAssets(\Twig_Environment $twig, Blocklyduino $app)
 {
     $twig->addFunction(new \Twig_SimpleFunction('blocklyduino_lib', function ($blockly) use($app) {
         // implement whatever logic you need to determine the blocklyduino path
         return sprintf('%sblockly/apps/blocklyduino/%s', $app->url('home'), ltrim($blockly, '/'));
     }));
     $twig->addFunction(new \Twig_SimpleFunction('blockly_apps_lib', function ($blockly) use($app) {
         // implement whatever logic you need to determine the blockly apps path
         return sprintf('%sblockly/apps/%s', $app->url('home'), ltrim($blockly, '/'));
     }));
     $twig->addFunction(new \Twig_SimpleFunction('blockly_lib', function ($blockly) use($app) {
         // implement whatever logic you need to determine the blockly path
         return sprintf('%sblockly/%s', $app->url('home'), ltrim($blockly, '/'));
     }));
 }
Example #14
0
 /**
  * Main entry point for the BootFrames app, will construct request, routes and
  * twig environment then run.
  */
 public function run()
 {
     // parse the config
     $this->config = Yaml::parse(file_get_contents(BASE_DIR . '/config/config.yml'));
     // parse request
     $this->request = Http\Request::createFromGlobals();
     // do authorization
     $this->doAuth();
     // generate routing
     if ($this->config['routing_type'] == 'scan') {
         $this->routes = $this->templateScan();
     } else {
         if ($this->config['routing_type'] == 'yaml') {
             $this->routes = Yaml::parse(file_get_contents(BASE_DIR . '/config/routes.yml'));
         }
     }
     // setup twig environment
     $loader = new \Twig_Loader_Filesystem(BASE_DIR . '/templates');
     $twig = new \Twig_Environment($loader, $this->config['twig']);
     // add some useful globals
     $twig->addGlobal('request', $this->request);
     $twig->addGlobal('config', $this->config);
     $twig->addGlobal('routes', $this->routes);
     $twig->addGlobal('authenticated', isset($_GET['authenticated']));
     $twig->addGlobal('privileged', isset($_GET['privileged']));
     $twig->addGlobal('GET', $_GET);
     // add our custom twig functions
     $twig->addFunction(new \Twig_SimpleFunction('url', ['BootFrame\\Twig\\Url', 'url'], ['needs_context' => true]));
     $twig->addFunction(new \Twig_SimpleFunction('route', ['BootFrame\\Twig\\Url', 'route'], ['needs_context' => true]));
     $twig->addFunction(new \Twig_SimpleFunction('route_reverse', ['BootFrame\\Twig\\Url', 'route_reverse'], ['needs_context' => true]));
     // path to match for routing
     $path = $this->request->getPathInfo();
     $route = $this->matchRoute($path, $this->routes);
     // render a twig template
     if ($route !== NULL) {
         $response = new Http\Response($twig->render($route['template']));
     } else {
         // render index
         if ($this->request->getPathInfo() == '/') {
             $response = new Http\Response($twig->render('index.html.twig'));
             // 404
         } else {
             $response = new Http\Response($twig->render('404.html.twig'), Http\Response::HTTP_NOT_FOUND);
         }
     }
     // send the response
     $response->send();
 }
Example #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;
     }
 }
Example #16
0
 /**
  * Spawns a new instance of Twig.
  *
  * @return object
  **/
 protected function spawn()
 {
     // register the Twig autoloader.
     Twig_Autoloader::register();
     // Init the Twig loader.
     $loader = new Twig_Loader_String();
     // check if the cache dir is set.
     if ($this->compile_dir) {
         if (is_null($this->debug)) {
             $this->debug = is_dev_mode();
         }
         $twig = new Twig_Environment($loader, array('autoescape' => FALSE, 'cache' => $this->compile_dir, 'debug' => $this->debug, 'charset' => $this->charset, 'base_template_class' => $this->base_template_class, 'strict_variables' => $this->strict_variables, 'autoescape' => $this->autoescape, 'optimizations' => $this->optimizations));
     } else {
         $twig = new Twig_Environment($loader, array('autoescape' => FALSE));
     }
     // init all functions as Twig functions.
     foreach ($this->allowed_functions as $function) {
         $twig->addFunction($function, new Twig_Function_Function($function));
     }
     // setup debugger
     $twig->addExtension(new Twig_Extension_Debug());
     // setup the Lexer
     $lexer = new Twig_Lexer($twig, $this->delimiters);
     $twig->setLexer($lexer);
     // finally, return the object.
     return $twig;
 }
Example #17
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();
 }
Example #18
0
 /**
  * @param  \Twig_Environment
  */
 public static function setTwigEnvironment(\Twig_Environment $twig)
 {
     $twig->addExtension(new \Twig_Extensions_Extension_Text());
     $twig->addFunction(new \Twig_SimpleFunction('markdown', '\\Nyaan\\View\\Markdown::render', ['is_safe' => ['html']]));
     //$twig->addFilter(new \Twig_SimpleFilter('caption_convert', '\MobileNovel\Service\NovelService::convertCaption'), ['is_safe' => ['html']]);
     parent::setTwigEnvironment($twig);
 }
Example #19
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);
 }
Example #20
0
 public function __construct($data = array())
 {
     parent::__construct($data);
     $dirs = Zend_Registry::get('dirs');
     $template = Zend_Registry::get('theme');
     $config = Zend_Registry::get('config');
     $qool_module = Zend_Registry::get('Qool_Module');
     // Class Constructor.
     // These automatically get set with each new instance.
     $loader = new Twig_Loader_Filesystem(APPL_PATH . $dirs['structure']['templates'] . DIR_SEP . $qool_module . DIR_SEP . $template . DIR_SEP);
     $twig = new Twig_Environment($loader, array('cache' => APPL_PATH . $dirs['structure']['cache'] . DIR_SEP . 'twig' . DIR_SEP));
     $lexer = new Twig_Lexer($twig, array('tag_comment' => array('<#', '#>}'), 'tag_block' => array('<%', '%>'), 'tag_variable' => array('<<', '>>')));
     $twig->setLexer($lexer);
     include_once APPL_PATH . $dirs['structure']['lib'] . DIR_SEP . 'Qool' . DIR_SEP . 'Template' . DIR_SEP . 'template.php';
     if (file_exists(APPL_PATH . $dirs['structure']['templates'] . DIR_SEP . $qool_module . DIR_SEP . $template . DIR_SEP . 'functions.php')) {
         include_once APPL_PATH . $dirs['structure']['templates'] . DIR_SEP . $qool_module . DIR_SEP . $template . DIR_SEP . 'functions.php';
     }
     $funcs = get_defined_functions();
     foreach ($funcs['user'] as $k => $v) {
         $twig->addFunction($v, new Twig_Function_Function($v));
     }
     $this->_twig = $twig;
     $this->assign('config', $config);
     Zend_Registry::set('tplExt', 'html');
 }
Example #21
0
 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);
 }
Example #22
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);
 }
Example #23
0
 private function template()
 {
     $config = new Config($this->registry);
     $twigPath = $config->getTWIGPath();
     $this->themeUrl = $this->registry->siteUrl . 'themes/' . $this->registry->template . '/';
     $this->isAjaxRequest = $this->registry->dispatcher->isAjaxRequest();
     require $twigPath;
     \Twig_Autoloader::register();
     $loader = new \Twig_Loader_Filesystem($this->getTemplate());
     $twig = new \Twig_Environment($loader);
     $urlFunction = new \Twig_SimpleFunction('url', function ($ctrl_action, $paramsArray = NULL) {
         $ctrl_action = explode('/', $ctrl_action);
         $controller = $ctrl_action[0] . '/';
         $action = $ctrl_action[1] . '/';
         $params = '';
         if (isset($paramsArray)) {
             $params .= '?';
             foreach ($paramsArray as $key => $value) {
                 $params .= $key . '=' . $value;
                 if (end($paramsArray) != $value) {
                     $params .= '&';
                 }
             }
         }
         $url = $this->registry->siteUrl . $controller . $action . $params;
         return $url;
     });
     $twig->addFunction($urlFunction);
     $template = $twig->loadTemplate($this->getView());
     return $template;
 }
Example #24
0
 protected function getEnvironment()
 {
     $env = new Twig_Environment();
     $env->addFunction(new Twig_Function('anonymous', function () {
     }));
     return $env;
 }
Example #25
0
 protected function addFunctions(\Twig_Environment $twig)
 {
     $functions = get_defined_functions()['user'];
     array_map(function ($name) use($twig) {
         $function = new \Twig_SimpleFunction($name, $name);
         $twig->addFunction($function);
     }, $functions);
 }
Example #26
0
 /**
  * Add a function to our Twig environment
  *
  * @param string $name - Name to access in Twig
  * @param callable $func - function definition
  * @param array $is_safe
  * @return Lens
  */
 public function func(string $name, $func = null, $is_safe = ['html']) : self
 {
     if (empty($func)) {
         $func = '\\Airship\\LensFunctions\\' . $name;
     }
     $this->twigEnv->addFunction(new \Twig_SimpleFunction($name, $func, ['is_safe' => $is_safe]));
     return $this;
 }
Example #27
0
 /**
  * Add custom function to twig view
  */
 private function addUserFunctions()
 {
     foreach ($this->add_user_functions as $function) {
         if (function_exists($function)) {
             $this->twig->addFunction(new \Twig_SimpleFunction($function, $function));
         }
     }
 }
Example #28
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');
 }
 /**
  *
  *
  * @param Twig_Environment $twig
  * @return Twig_Environment
  */
 public function add_to_twig($twig)
 {
     $wrapper = $this;
     $twig->addFunction(new Twig_SimpleFunction($this->_function, function () use($wrapper) {
         return call_user_func_array(array($wrapper, 'call'), func_get_args());
     }));
     return $twig;
 }
Example #30
0
 /**
  * Register Twig helper methods.
  *
  * @return void
  */
 protected function registerHelpers()
 {
     $function = new TwigFunction('first', [$this, 'firstHelper']);
     $this->twig->addFunction($function);
     $function = new TwigFunction('ui', [$this, 'uiHelper']);
     $this->twig->addFunction($function);
     $colour = new \Raincolour\Twig\Globals\Colour($this->theme->get());
     $this->twig->addGlobal('colour', $colour);
 }