【问题标题】:How to load a template from full path in the template engine TWIG如何在模板引擎 TWIG 中从完整路径加载模板
【发布时间】:2011-10-27 06:04:29
【问题描述】:

我想知道如何从完整路径加载模板(如 FILE 常量)。

实际上你必须像这样为模板设置一个“根”路径:

require_once '/path/to/lib/Twig/Autoloader.php';
Twig_Autoloader::register();

$loader = new Twig_Loader_Filesystem('/path/to/templates');
$twig = new Twig_Environment($loader, array(
   'cache' => '/path/to/compilation_cache',
));

然后:

$template = $twig->loadTemplate('index.html');
echo $template->render(array('the' => 'variables', 'go' => 'here'));

我想用完整路径而不是文件名来调用 loadTemplate 方法。

我该怎么办?

我不想为这样的事情创建自己的加载器..

谢谢

【问题讨论】:

    标签: php templates template-engine twig


    【解决方案1】:

    就这样做吧:

    $loader = new Twig_Loader_Filesystem('/');
    

    这样 ->loadTemplate() 将相对于/ 加载模板。

    或者,如果您希望能够同时加载具有相对路径和绝对路径的模板:

    $loader = new Twig_Loader_Filesystem(array('/', '/path/to/templates'));
    

    【讨论】:

    • 那行不通,因为我在本地工作,而且我有一个绝对路径,如“J:/wamp/www/CHEVAUX/wp-content/plugins/.../index.twig”(我得到它来自 file const),因此它不接受该路径之前的任何字符。
    • 试试$loader = new Twig_Loader_Filesystem('J:/');
    • 不工作 :( 加载程序这样做:“if (is_file($path.'/'.$name)) {..” 所以我需要类似“if (is_file($name) ) {.."
    • 如果$path是你文件系统的根,那么$path . '/' . $name == $name(我猜即使在windows上,"J:/" . "/some/file""J:/some/file"一样。设置@987654330 @ 到您操作系统上文件系统的根目录。
    • 是的,这会起作用,但如果我移动它,它会再次崩溃。我决定创建一个新的加载器。我将它贴在下面。谢谢
    【解决方案2】:

    这是一个加载给定绝对(或非)路径的加载器:

    <?php
    
    
    class TwigLoaderAdapter implements Twig_LoaderInterface
    {
        protected $paths;
        protected $cache;
    
        public function __construct()
        {
    
        }
    
        public function getSource($name)
        {
            return file_get_contents($this->findTemplate($name));
        }
    
        public function getCacheKey($name)
        {
            return $this->findTemplate($name);
        }
    
        public function isFresh($name, $time)
        {
            return filemtime($this->findTemplate($name)) < $time;
        }
    
        protected function findTemplate($path)
        {
            if(is_file($path)) {
                if (isset($this->cache[$path])) {
                    return $this->cache[$path];
                }
                else {
                    return $this->cache[$path] = $path;
                }
            }
            else {
                throw new Twig_Error_Loader(sprintf('Unable to find template "%s".', $path));
            }
        }
    
    }
    
    ?>
    

    【讨论】:

    • 我该如何实践?我是否必须为该 sn-p 创建一个新文件,或者它是如何工作的?抱歉,我是 Twig 新手,遇到了完全相同的问题..
    【解决方案3】:

    扩展加载器比修改库更好:

    <?php
    
    /**
     * Twig_Loader_File
     */
    class Twig_Loader_File extends Twig_Loader_Filesystem
    {
        protected function findTemplate($name)
        {
            if(isset($this->cache[$name])) {
                return $this->cache[$name];
            }
    
            if(is_file($name)) {
                $this->cache[$name] = $name;
                return $name;
            }
    
            return parent::findTemplate($name);
        }
    } 
    

    【讨论】:

      【解决方案4】:

      这对我有用(Twig 1.x):

      final class UtilTwig
      {
          /**
           * @param string $pathAbsTwig
           * @param array $vars
           * @return string
           * @throws \Twig\Error\LoaderError
           * @throws \Twig\Error\RuntimeError
           * @throws \Twig\Error\SyntaxError
           */
          public static function renderTemplate(string $pathAbsTwig, array $vars)
          {
              $loader = new Twig_Loader_Filesystem([''], '/');
              $twig = new Twig_Environment($loader);
              $template = $twig->loadTemplate($pathAbsTwig);
              $mailBodyHtml = $template->render($vars);
      
              return $mailBodyHtml;
          }
      }
      

      用法:

      $htmlBody = UtilTwig::renderTemplate('/absolute/path/to/template.html.twig', [
          'some' => 'var', 
          'foo' => 'bar'
      ]);
      

      【讨论】:

        【解决方案5】:

        在 Symfony(5.4 版)的配置中,使用您的模板将新的核心路径添加到文件夹。

        twig:
            default_path: '%kernel.project_dir%/templates'
            paths:
                '%kernel.project_dir%/src/Service/SendEmail/EmailTpl': EmailTpl
        

        现在你可以渲染模板了。

        在控制器中:

        $this->render('@EmailTpl/bobo_reg.html.twig')
        

        在任何其他地方:

        $content = $this->container->get('twig')->render('@EmailTpl/bobo_reg.html.twig');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-07-06
          • 1970-01-01
          • 1970-01-01
          • 2014-07-20
          • 1970-01-01
          • 2012-03-09
          • 2012-10-28
          相关资源
          最近更新 更多