简体   繁体   中英

Twig template engine and truncating text

I've been learning how to use Twig, as per this site . This is my code, a variation on the tutorial's:

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());
}
?>

and the template page:

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

Auto-escaping is enabled through:

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

However, I would like to truncate the text and have tried to install the Text extension by adding it to the extensions directory but I'm not sure how to get it working so I could do:

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

etc.

I did look on Google, but what I found was pertinent to Symfony, and I'm using Twig, simply to get a feel for it as a templating engine.

What should I do to enable truncating of text in Twig?

you already have half of the solution, as it seems you are only missing to add the extension, which is basically the same as you did with the escaper extension:

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

should do the trick.

enable it's service in config.yml :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM