setLoader() public method

Sets the Loader instance.
public setLoader ( Twig_LoaderInterface $loader )
$loader Twig_LoaderInterface A Twig_LoaderInterface instance
コード例 #1
0
 /**
  * Render a string
  *
  * A special option in the $locals array can be used to define the Twital adapter to use.
  * The array key is `__twital-adapter`, and the value is an instance of `\Goetas\Twital\SourceAdapter`
  *
  * @param string $template The template content to render
  * @param array $locals The variable to use in template
  * @return null|string
  *
  * @throws \Twig_Error_Loader
  * @throws \Twig_Error_Runtime
  * @throws \Twig_Error_Syntax
  */
 public function render($template, array $locals = array())
 {
     if (array_key_exists('__twital-adapter', $locals)) {
         $this->stringLoader->addSourceAdapter('/.*/', $locals['__twital-adapter']);
     }
     // Render the file using the straight string.
     $this->environment->setLoader($this->stringLoader);
     return $this->environment->render($template, $locals);
 }
コード例 #2
0
 /**
  * add a directory to template search dirs
  * @param string $directory
  * @param bool|true $primary
  * @return ITemplateEngine|void
  */
 public function addDir($directory, $primary = true)
 {
     if ($primary) {
         $this->twigLoader->prependPath($directory);
     } else {
         $this->twigLoader->addPath($directory);
     }
     $this->twigEnv->setLoader($this->twigLoader);
     return $this;
 }
 protected function setUp()
 {
     if (!class_exists('Twig_Environment')) {
         $this->markTestSkipped('Twig is not installed.');
     }
     $this->mediaStorage = new FilesystemMediaStorage(__DIR__ . "/fixtures/stored", "/project/web/media/", "http://localhost/project/web/media/", FALSE);
     $this->twig = new \Twig_Environment();
     $this->twig->setLoader(new \Twig_Loader_Filesystem(__DIR__ . '/fixtures/templates'));
     $this->twig->addExtension(new TwigMediaStorageExtension($this->mediaStorage, TRUE));
 }
コード例 #4
0
 protected function setUp()
 {
     if (!class_exists('Twig_Environment')) {
         $this->markTestSkipped('Twig is not installed.');
     }
     $this->mapper = $this->getMock('Midgard\\CreatePHP\\RdfMapperInterface');
     $xmlDriver = new RdfDriverXml(array(__DIR__ . '/../../Metadata/rdf-twig'));
     $this->factory = new RdfTypeFactory($this->mapper, $xmlDriver);
     $this->twig = new \Twig_Environment();
     $this->twig->setLoader(new \Twig_Loader_Filesystem(__DIR__ . '/templates'));
     $this->twig->addExtension(new CreatephpExtension($this->factory));
 }
コード例 #5
0
ファイル: Twig.php プロジェクト: Nully/zf_twig
 /**
  * 表示するためのファイルを組み立て
  *
  * @access protected
  */
 protected function _run()
 {
     // 引数のファイルパスをview scriptまでのパスとcontroller/action.:suffixの形式に分断する
     $paths = $this->_parseFilePath(func_get_arg(0));
     // view scriptまでのパスを指定
     $this->_twig->setLoader(new Twig_Loader_Filesystem($paths["path"]));
     // 登録した配列の0番目のViewScriptをテンプレートとして読み込み
     $template = $this->_twig->loadTemplate($paths["file"]);
     // APPLICATION_ENVをTwigから利用出来るようにするため変数に入れておく
     $this->env = APPLICATION_ENV;
     echo $template->render($this->getVars());
 }
コード例 #6
0
 /**
  * @param  \Twig_Environment $env
  * @param                    $context
  * @param  FormView          $form
  * @param  string            $formVariableName
  * @return array
  */
 public function render(\Twig_Environment $env, $context, FormView $form, $formVariableName = 'form')
 {
     $this->formVariableName = $formVariableName;
     $this->formConfig = new FormConfig();
     $this->context = $context;
     $this->env = $env;
     $tmpLoader = $env->getLoader();
     $env->setLoader(new \Twig_Loader_Chain([$tmpLoader, new \Twig_Loader_String()]));
     $this->renderBlock($form);
     $env->setLoader($tmpLoader);
     return $this->formConfig->toArray();
 }
コード例 #7
0
 /**
  * {@inheritdoc}
  */
 public function transform($text)
 {
     // Here we temporary changing twig environment loader to Chain loader with Twig_Loader_Array as first loader, which contains only one our template reference
     $oldLoader = $this->twig->getLoader();
     $hash = sha1($text);
     $chainLoader = new \Twig_Loader_Chain();
     $chainLoader->addLoader(new \Twig_Loader_Array(array($hash => $text)));
     $chainLoader->addLoader($oldLoader);
     $this->twig->setLoader($chainLoader);
     $result = $this->twig->render($hash);
     $this->twig->setLoader($oldLoader);
     return $result;
 }
コード例 #8
0
 /**
  * @param \Twig_Environment $env
  * @param array             $context
  * @param FormView          $form
  * @param string            $formVariableName
  *
  * @return array
  */
 public function render(\Twig_Environment $env, $context, FormView $form, $formVariableName = 'form')
 {
     // remember current loader
     $originalLoader = $env->getLoader();
     // replace the loader
     $env->setLoader(new \Twig_Loader_Chain(array($originalLoader, new \Twig_Loader_String())));
     // build blocks
     $builder = new DataBlockBuilder(new TwigTemplateRenderer($env, $context), $formVariableName);
     $result = $builder->build($form);
     // restore the original loader
     $env->setLoader($originalLoader);
     return $result->toArray();
 }
コード例 #9
0
/**
 * Loads a template from a string.
 *
 * <pre>
 * {{ include(template_from_string("Hello {{ name }}")) }}
 * </pre>
 *
 * @param Twig_Environment $env      A Twig_Environment instance
 * @param string           $template A template as a string
 *
 * @return Twig_Template A Twig_Template instance
 */
function twig_template_from_string(Twig_Environment $env, $template)
{
    $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false));
    $loader = new Twig_Loader_Chain(array(new Twig_Loader_Array(array($name => $template)), $current = $env->getLoader()));
    $env->setLoader($loader);
    try {
        $template = $env->loadTemplate($name);
    } catch (Exception $e) {
        $env->setLoader($current);
        throw $e;
    }
    $env->setLoader($current);
    return $template;
}
コード例 #10
0
 protected function setUp()
 {
     if (!class_exists('Twig_Environment')) {
         $this->markTestSkipped('Twig is not installed.');
     }
     $this->am = $this->getMock('Assetic\\AssetManager');
     $this->fm = $this->getMock('Assetic\\FilterManager');
     $this->valueSupplier = $this->getMock('Assetic\\ValueSupplierInterface');
     $this->factory = new AssetFactory(__DIR__ . '/templates');
     $this->factory->setAssetManager($this->am);
     $this->factory->setFilterManager($this->fm);
     $this->twig = new \Twig_Environment();
     $this->twig->setLoader(new \Twig_Loader_Filesystem(__DIR__ . '/templates'));
     $this->twig->addExtension(new AsseticExtension($this->factory, array(), $this->valueSupplier));
 }
コード例 #11
0
 public function boot()
 {
     $configPath = __DIR__ . '/../config/form.php';
     $this->publishes([$configPath => config_path('form.php')], 'config');
     if ($this->app->bound(\Twig_Environment::class)) {
         /** @var \Twig_Environment $twig */
         $twig = $this->app->make(\Twig_Environment::class);
     } else {
         $twig = new \Twig_Environment(new \Twig_Loader_Chain([]));
     }
     $loader = $twig->getLoader();
     // If the loader is not already a chain, make it one
     if (!$loader instanceof \Twig_Loader_Chain) {
         $loader = new \Twig_Loader_Chain([$loader]);
         $twig->setLoader($loader);
     }
     $reflected = new \ReflectionClass(FormExtension::class);
     $path = dirname($reflected->getFileName()) . '/../Resources/views/Form';
     $loader->addLoader(new \Twig_Loader_Filesystem($path));
     /** @var TwigRenderer $renderer */
     $renderer = $this->app->make(TwigRendererInterface::class);
     $renderer->setEnvironment($twig);
     // Add the extension
     $twig->addExtension(new FormExtension($renderer));
     // trans filter is used in the forms
     $twig->addFilter(new \Twig_SimpleFilter('trans', 'trans'));
     // csrf_token needs to be replaced for Laravel
     $twig->addFunction(new \Twig_SimpleFunction('csrf_token', 'csrf_token'));
     $this->registerBladeDirectives();
 }
コード例 #12
0
 private function getEnv()
 {
     $env = new \Twig_Environment();
     $env->addTokenParser(new TwigJsTokenParser());
     $env->setLoader(new \Twig_Loader_String());
     return $env;
 }
コード例 #13
0
/**
 * Loads a template from a string.
 *
 * <pre>
 * {% include template_from_string("Hello {{ name }}") }}
 * </pre>
 *
 * @param Twig_Environment $env      A Twig_Environment instance
 * @param string           $template A template as a string
 *
 * @return Twig_Template A Twig_Template instance
 */
function twig_template_from_string(Twig_Environment $env, $template)
{
    static $loader;
    if (null === $loader) {
        $loader = new Twig_Loader_String();
    }
    $current = $env->getLoader();
    $env->setLoader($loader);
    try {
        $template = $env->loadTemplate($template);
    } catch (Exception $e) {
        $env->setLoader($current);
        throw $e;
    }
    $env->setLoader($current);
    return $template;
}
コード例 #14
0
ファイル: twig.php プロジェクト: schpill/standalone
 /**
  * @param string $string
  * @return string
  */
 public function renderString($string)
 {
     // no rendering if empty
     if (empty($string)) {
         return $string;
     }
     // see Twig\Extensions\Twig_Extension_StringLoader
     $name = '__twig_string__';
     // get current loader
     $loader = $this->environment->getLoader();
     // set loader chain with new array loader
     $this->environment->setLoader(new Twig_Loader_Chain(array(new Twig_Loader_Array(array($name => $string)), $loader)));
     // render string
     $rendered = $this->environment->render($name);
     // reset current loader
     $this->environment->setLoader($loader);
     return $rendered;
 }
コード例 #15
0
 /**
  * Sets the parser for the environment to Twig_Loader_String, and parsed the string $string.
  * 
  * @param \Twig_Environment $environment
  * @param array $context
  * @param string $string
  * @return string 
  */
 protected function parseString(\Twig_Environment $environment, $context, $string)
 {
     try {
         $environment->setLoader(new \Twig_Loader_String());
         return $environment->render($string, $context);
     } catch (\Exception $exc) {
         return null;
     }
 }
コード例 #16
0
ファイル: TwigHandler.php プロジェクト: minond/fabrico
 /**
  * {@inheritDoc}
  */
 public function render(Application &$app, $file, array $data = [])
 {
     $cdir = getcwd();
     $twig = new Twig();
     $twig->setLoader(new Loader($cdir));
     $app->initialize('twig', ['twig' => &$twig]);
     $template = $twig->loadTemplate($file);
     return $template->render($data);
 }
コード例 #17
0
 /**
  * Add a new namespace to the loader.
  *
  * @param  \TwigBridge\StringView\StringView  $view
  * @return \TwigBridge\Twig\Template
  */
 public function resolveTemplate(StringView $view)
 {
     $currentLoader = $this->twig->getLoader();
     $loader = new Loader($view);
     $this->twig->setLoader($loader);
     $template = $this->twig->resolveTemplate($view->getName());
     $this->twig->setLoader($currentLoader);
     return $template;
 }
コード例 #18
0
 protected final function parse($file, $debug = false)
 {
     $content = file_get_contents(__DIR__ . '/Fixture/' . $file);
     $env = new \Twig_Environment();
     $env->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
     $env->addExtension(new TranslationExtension($translator, $debug));
     $env->setLoader(new \Twig_Loader_String());
     return $env->parse($env->tokenize($content));
 }
コード例 #19
0
ファイル: Template.php プロジェクト: varvanin/currycms
 /**
  * Load template from string using the shared environment.
  *
  * @param string $template
  * @return Curry_Twig_Template
  */
 public static function loadTemplateString($template)
 {
     self::getSharedEnvironment();
     $loader = self::$twig->getLoader();
     self::$twig->setLoader(new Twig_Loader_String());
     $tpl = self::$twig->loadTemplate($template);
     self::$twig->setLoader($loader);
     return $tpl;
 }
コード例 #20
0
 /**
  * @dataProvider getGenerationTests
  */
 public function testGenerate($inputFile, $outputFile)
 {
     $env = new \Twig_Environment();
     $env->addExtension(new \Twig_Extension_Core());
     $env->addExtension(new TwigJsExtension());
     $env->setLoader(new \Twig_Loader_Filesystem(__DIR__ . '/Fixture/templates'));
     $env->setCompiler(new JsCompiler($env));
     $source = file_get_contents($inputFile);
     $this->assertEquals(file_get_contents($outputFile), $env->compileSource($source, $inputFile));
 }
コード例 #21
0
ファイル: TwigEngine.php プロジェクト: vvval/spiral
 /**
  * {@inheritdoc}
  *
  * @return $this
  */
 public function setLoader(LoaderInterface $loader)
 {
     if (!empty($this->modifiers)) {
         //Let's prepare source before giving it to Stempler
         //todo: make sure not used until needed?
         $loader = new ModifiableLoader($loader, $this->getModifiers());
     }
     $this->twig->setLoader($this->loader = $loader);
     return $this;
 }
コード例 #22
0
 private function registerWidgetTemplates(\Twig_Environment &$twigEnvironment)
 {
     $currentLoader = $twigEnvironment->getLoader();
     if ($currentLoader instanceof \Twig_Loader_Filesystem) {
         $currentLoader->addPath(__DIR__ . '/../widgets', 'assetwidgets');
     } elseif ($currentLoader instanceof \Twig_Loader_Chain) {
         $fsloader = new \Twig_Loader_Filesystem();
         $fsloader->addPath(__DIR__ . '/../widgets', 'assetwidgets');
         $currentLoader->addLoader($fsloader);
     }
     $twigEnvironment->setLoader($currentLoader);
 }
コード例 #23
0
 /**
  * Render
  *
  * @access public
  * @param string $template
  * @return string $html
  */
 public function render($template)
 {
     $environment = ['post' => $_POST, 'get' => $_GET, 'cookie' => $_COOKIE, 'server' => $_SERVER];
     $environment = array_merge($environment, $this->environment);
     if ($this->i18n_available === true and $this->translation !== null) {
         $environment['translation'] = $this->translation;
         $environment['language'] = $this->translation->language;
     }
     if (isset($_SESSION)) {
         $environment['session'] = $_SESSION;
     }
     $this->twig->setLoader($this->filesystem_loader);
     $this->twig->addGlobal('env', $environment);
     return $this->twig->render($template, $this->variables);
 }
コード例 #24
0
 private function extract($directory)
 {
     $twig = new \Twig_Environment();
     $twig->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
     $twig->addExtension(new TranslationExtension($translator));
     $loader = new \Twig_Loader_Filesystem(realpath(__DIR__ . "/Fixture/SimpleTest/Resources/views/"));
     $twig->setLoader($loader);
     $docParser = new DocParser();
     $docParser->setImports(array('desc' => 'JMS\\TranslationBundle\\Annotation\\Desc', 'meaning' => 'JMS\\TranslationBundle\\Annotation\\Meaning', 'ignore' => 'JMS\\TranslationBundle\\Annotation\\Ignore'));
     $docParser->setIgnoreNotImportedAnnotations(true);
     $factory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
     $extractor = new FileExtractor($twig, new NullLogger(), array(new DefaultPhpFileExtractor($docParser), new TranslationContainerExtractor(), new TwigFileExtractor($twig), new ValidationExtractor($factory), new FormExtractor($docParser)));
     $extractor->setDirectory($directory);
     return $extractor->extract();
 }
コード例 #25
0
ファイル: AppFormFactory.php プロジェクト: pavgra/2nova-test
 /**
  * Adds extensions required for proper work with FormFactory to Twig template engine
  * @param CsrfTokenManager $csrfTokenManager
  */
 private function extendTwig($csrfTokenManager)
 {
     $translator = new Translator($this->lang);
     $translator->addLoader('xlf', new XliffFileLoader());
     $translator->addResource('xlf', $this->componentDir['form'] . '/Resources/translations/validators.en.xlf', 'en', 'validators');
     $translator->addResource('xlf', $this->componentDir['validator'] . '/Resources/translations/validators.en.xlf', 'en', 'validators');
     $formTheme = 'bootstrap_3_layout.html.twig';
     //'form_div_layout.html.twig';
     $formEngine = new TwigRendererEngine([$formTheme]);
     $twigLoader = $this->twig->getLoader();
     $newTwigLoader = new \Twig_Loader_Chain([$twigLoader, new \Twig_Loader_Filesystem([$this->componentDir['twigBridge'] . '/Resources/views/Form'])]);
     $this->twig->setLoader($newTwigLoader);
     $formEngine->setEnvironment($this->twig);
     $this->twig->addExtension(new TranslationExtension($translator));
     $this->twig->addExtension(new FormExtension(new TwigRenderer($formEngine, $csrfTokenManager)));
 }
コード例 #26
0
ファイル: TwigView.php プロジェクト: bgillet/slim-twig
 /**
  * Set one or more directory where renderer will look for templates.
  * Be aware that calling this method replaces currently set directories.
  * @param string|array $directory A single directory (string) or an array using namespace as key and path as value.
  */
 public function setTemplatesDirectory($directory)
 {
     if (StringUtils::emptyOrSpaces($directory)) {
         $directory = array();
     }
     if (!is_array($directory)) {
         $directory = array($directory);
     }
     $this->_loader = new \Twig_Loader_Filesystem();
     foreach ($directory as $namespace => $path) {
         if (StringUtils::emptyOrSpaces($namespace)) {
             $this->_loader->addPath($path);
         } else {
             $this->_loader->addPath($path, trim($namespace));
         }
     }
     $this->_renderer->setLoader($this->_loader);
 }
コード例 #27
0
 private function extract($directory)
 {
     $twig = new \Twig_Environment();
     $twig->addExtension(new SymfonyTranslationExtension($translator = new IdentityTranslator(new MessageSelector())));
     $twig->addExtension(new TranslationExtension($translator));
     $loader = new \Twig_Loader_Filesystem(realpath(__DIR__ . "/Fixture/SimpleTest/Resources/views/"));
     $twig->setLoader($loader);
     $docParser = new DocParser();
     $docParser->setImports(array('desc' => 'JMS\\TranslationBundle\\Annotation\\Desc', 'meaning' => 'JMS\\TranslationBundle\\Annotation\\Meaning', 'ignore' => 'JMS\\TranslationBundle\\Annotation\\Ignore'));
     $docParser->setIgnoreNotImportedAnnotations(true);
     //use correct factory class depending on whether using Symfony 2 or 3
     if (class_exists('Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory')) {
         $metadataFactoryClass = 'Symfony\\Component\\Validator\\Mapping\\Factory\\LazyLoadingMetadataFactory';
     } else {
         $metadataFactoryClass = 'Symfony\\Component\\Validator\\Mapping\\ClassMetadataFactory';
     }
     $factory = new $metadataFactoryClass(new AnnotationLoader(new AnnotationReader()));
     $extractor = new FileExtractor($twig, new NullLogger(), array(new DefaultPhpFileExtractor($docParser), new TranslationContainerExtractor(), new TwigFileExtractor($twig), new ValidationExtractor($factory), new FormExtractor($docParser)));
     $extractor->setDirectory($directory);
     return $extractor->extract();
 }
コード例 #28
0
ファイル: TwigUtil.php プロジェクト: payum/core
 /**
  * @param \Twig_Environment $twig
  * @param string[] $paths
  */
 public static function registerPaths(\Twig_Environment $twig, array $paths)
 {
     if (false == static::$storage) {
         static::$storage = new \SplObjectStorage();
     }
     $storage = static::$storage;
     /** @var \Twig_Loader_Filesystem $payumLoader */
     $payumLoader = $twig && isset($storage[$twig]) ? $storage[$twig] : new \Twig_Loader_Filesystem();
     foreach ($paths as $namespace => $path) {
         $payumLoader->addPath($path, $namespace);
     }
     if (false == isset($storage[$twig])) {
         $currentLoader = $twig->getLoader();
         if ($currentLoader instanceof \Twig_Loader_Chain) {
             $currentLoader->addLoader($payumLoader);
         } else {
             $twig->setLoader(new \Twig_Loader_Chain([$currentLoader, $payumLoader]));
         }
         $storage->attach($twig, $payumLoader);
     }
 }
コード例 #29
0
ファイル: LintCommand.php プロジェクト: ninvfeng/symfony
 private function validate(\Twig_Environment $twig, $template, $file)
 {
     $realLoader = $twig->getLoader();
     try {
         $temporaryLoader = new \Twig_Loader_Array(array((string) $file => $template));
         $twig->setLoader($temporaryLoader);
         $nodeTree = $twig->parse($twig->tokenize($template, (string) $file));
         $twig->compile($nodeTree);
         $twig->setLoader($realLoader);
     } catch (\Twig_Error $e) {
         $twig->setLoader($realLoader);
         return array('template' => $template, 'file' => $file, 'valid' => false, 'exception' => $e);
     }
     return array('template' => $template, 'file' => $file, 'valid' => true);
 }
コード例 #30
0
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
require_once __DIR__ . '/../tests/bootstrap.php';
$_SERVER['TWIG_LIB'] = __DIR__ . '/../vendor/twig/twig/lib';
if (!isset($_SERVER['TWIG_LIB'])) {
    throw new \RuntimeException('$_SERVER["TWIG_LIB"] must be set.');
}
$env = new Twig_Environment();
$env->setLoader(new Twig_Loader_Filesystem(array(__DIR__ . '/../src-js/templates/twig')));
$env->addExtension(new Twig_Extension_Core());
$handler = new TwigJs\CompileRequestHandler($env, new TwigJs\JsCompiler($env));
foreach (new RecursiveDirectoryIterator(__DIR__ . '/../src-js/templates/twig', RecursiveDirectoryIterator::SKIP_DOTS) as $file) {
    if ('.twig' !== substr($file, -5)) {
        continue;
    }
    $request = new TwigJs\CompileRequest(basename($file), file_get_contents($file));
    file_put_contents(__DIR__ . '/../src-js/templates/js/' . basename($file, '.twig') . '.js', $handler->process($request));
    file_put_contents(__DIR__ . '/../src-js/templates/php/' . basename($file, '.twig') . '.php', $env->compileSource(file_get_contents($file), basename($file)));
}
// port over selected twig integration tests
$testsToPort = array('expressions/array');
$pathToFixtures = realpath($_SERVER['TWIG_LIB'] . '/../test/Twig/Tests/Fixtures');
$targetDir = realpath(__DIR__ . '/../src-js/templates/integration');
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pathToFixtures, RecursiveDirectoryIterator::SKIP_DOTS)) as $file) {