Reputation: 1659
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>
and this is the code behind it:
<?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());
}
?>
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?
All help is appreciated!
Upvotes: 0
Views: 6162
Reputation: 5280
You can truncate text in your Twig template like this:
{{ d.modelinfo[:10] }}
That should return the first 10 characters in d.modelinfo
.
Take a look at the slice filter documentation page.
Upvotes: 7
Reputation: 1754
Twig has a truncate filter but you have to enable the text extensions by adding the following to your config.yml file.
services:
twig.extension.text:
class: Twig_Extensions_Extension_Text
tags:
- { name: twig.extension }
Then in your template you can use the truncate filter and pass it an integer which denotes the length of the truncation.
{{ d.modelinfo|truncate(50) }}
Upvotes: 4