【问题标题】:Twig template engine and truncating textTwig 模板引擎和截断文本
【发布时间】:2012-10-28 21:36:52
【问题描述】:

根据this site,我一直在学习如何使用 Twig。 这是我的代码,是教程的变体:

index.php:

<?php
// include and register Twig auto-loader
include 'Twig/Autoloader.php';
Twig_Autoloader::register();

// attempt a connection
try {
  $dbh = new PDO('mysql:dbname=articles;host=localhost', 'test', 'testing');
} catch (PDOException $e) {
  echo "Error: Could not connect. " . $e->getMessage();
}

// set error mode
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// attempt some queries
try {
  // execute SELECT query
  // store each row as an object
  $sql = "SELECT * FROM schedule GROUP BY airtime";
  $sth = $dbh->query($sql);
  while ($row = $sth->fetchObject()) {
    $data[] = $row;
  }

  // close connection, clean up
  unset($dbh); 

  // define template directory location
  $loader = new Twig_Loader_Filesystem('templates');

  // initialize Twig environment
  $twig = new Twig_Environment($loader);
  $escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);
  // load template
  $template = $twig->loadTemplate('countries.tmpl');


  // set template variables
  // render template
  echo $template->render(array (
    'data' => $data
  ));

} catch (Exception $e) {
  die ('ERROR: ' . $e->getMessage());
}
?>

和模板页面:

 {% for d in data %}
      <tr>
        <td>{{ d.articleid }}</td>
        <td>{{ d.articlename }}</td>
        <td>{{ d.info }}</td>
      </tr> 
      {% endfor %}

通过以下方式启用自动转义:

     $twig = new Twig_Environment($loader);
  $escaper = new Twig_Extension_Escaper(false);
$twig->addExtension($escaper);

但是,我想截断文本并尝试通过将文本扩展添加到扩展目录来安装它,但我不知道如何让它工作,所以我可以这样做:

{{d.info|truncate(40)}}

等等

我确实在 Google 上查看过,但我发现与 Symfony 相关,我使用 Twig 只是为了感受一下它作为模板引擎的感觉。

我应该怎么做才能在 Twig 中启用文本截断功能?

【问题讨论】:

    标签: php twig templating templating-engine


    【解决方案1】:

    在 config.yml 中启用它的服务:

    services:
        twig.extension.text:
            class: Twig_Extensions_Extension_Text
            tags:
                    - { name: twig.extension }
    

    【讨论】:

      【解决方案2】:

      您已经有了一半的解决方案,因为您似乎只是缺少添加扩展名,这与您使用转义器扩展名基本相同:

      $twig->addExtension(new Twig_Extensions_Extension_Text()); 
      

      应该可以解决问题。

      【讨论】:

      • 已修复此问题,但必须使用文本扩展名进行修改!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 2011-07-11
      • 2021-06-18
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多