树枝和截断文本 [英] Twig and truncating text

查看:31
本文介绍了树枝和截断文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 MAMP 的本地主机上创建了这个简单的 Twig 页面:

I created this simple Twig page on localhost on MAMP:

   <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>

这是它背后的代码:

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

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

However, I am planning to truncate the text in the modelinfo field, I believe this can be done in MySQL with the select LEFT function, but how should I modify the query?

感谢所有帮助!

推荐答案

您可以像这样截断 Twig 模板中的文本:

You can truncate text in your Twig template like this:

{{ d.modelinfo[:10] }}

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

That should return the first 10 characters in d.modelinfo.

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

这篇关于树枝和截断文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆