树枝和截断文字

ave*_*808 0 mysql twig

我在MAMP上的localhost上创建了这个简单的Twig页面:

   <html>
  <head>
    <style type="text/css">
      table {
        border-collapse: collapse;
      }        
      tr.heading {      
        font-weight: bolder;
      }        
      td {
        border: 0.5px solid black;
        padding: 0 0.5em;
      }    
    </style>  
  </head>
  <body>
    <h2>Automobiles</h2>
    <table>
      <tr class="heading">
        <td>Vehicle</td>
        <td>Model</td>
        <td>Price</td>
      </tr> 
      {% for d in data %}
      <tr>
        <td>{{ d.manufacturer|escape }}</td>
        <td>{{ d.model|escape }}</td>
        <td>{{ d.modelinfo|raw }}</td>
      </tr> 
      {% endfor %}
    </table>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

这是它背后的代码:

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

// attempt a connection
try {
  $dbh = new PDO('mysql:dbname=world;host=localhost', 'root', 'mypass');
} 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 manufacturer, model, price FROM automobiles";
  $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);

  // load template
  $template = $twig->loadTemplate('cars.html');

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

} catch (Exception $e) {
  die ('ERROR: ' . $e->getMessage());
}
?>
Run Code Online (Sandbox Code Playgroud)

但是,我打算在modelinfo字段中截断文本,我相信这可以在MySQL中使用select LEFT函数完成,但是我该如何修改查询呢?

所有帮助表示赞赏!

Jua*_*osa 7

您可以截断Twig模板中的文本,如下所示:

{{ d.modelinfo[:10] }}
Run Code Online (Sandbox Code Playgroud)

这应该返回前10个字符d.modelinfo.

请查看切片过滤器文档页面.