Reputation: 5
I would like to ask how pass multiline(string with linebreaks) variable into twig template.
I'm filling string variable with cycle, I need it is with lineends.
foreach($rows as $row)
{
$popissouboru = $row['jmeno_souboru'];
$smernice.= $popissouboru.PHP_EOL;
}
Then I pass this variable to twigtemplate (HTML) where affected line looks like this
<p class="w3-text-black">{{ smernice }}</p>
But final output ignores the lineends and everything is in one line ...
Any idea how to pass linebreaks / ends ?
Thank you
Jan
Upvotes: 0
Views: 2712
Reputation: 629
You can generate the for-each-loop inside your twig template, too. If you want line breaks, you could create a table without borders and for each loop value you use one table row. This might be beyond your purpose, though. I'll try anyway. Maybe it helps:
{% for user in users %}
<table border="0">
<tr>
<td>{{ user.user_id }}</td>
</tr>
<tr>
<td>{{ user.user_name }}</td>
</tr>
<tr>
<td>{{ user.user_type }}</td>
</tr>
</table>
{% endfor %}
<?php
require_once 'vendor/autoload.php'; // automatically load pathes
require_once "utils/Database.class.php"; // include database configuration
// init twig
$loader = new Twig_Loader_Filesystem('template/'); // determines template path
//creates twig object and instances
$twig = new Twig_Environment($loader, array(
"debug" => "true",
));
$twig->addExtension(new Twig_Extension_Debug());
include "utils/injector.php"; //sql injection
/* ------- */
DatabaseLink::getInstance()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// fetch data from database
$stmt = DatabaseLink::getInstance()->query("SELECT * FROM user");
$userData = $stmt->fetchAll();
//template values
$templateName = "listUsers.twig";
$data = array(
"users" => $userData
);
//display
echo $twig->render($templateName, $data);
Upvotes: 0
Reputation: 19000
I just stumbled upon this when I searched for a solution to the very same problem. I add this as note to myself and for future readers:
If the actual problem is to get line-breaks in HTML simple use nl2br
{{ content | nl2br }}
or just generate the content in question with <br>
or <p>
-tags in the first place, as hinted by the OP.
If you just want to remove the newlines use replace
:
{{ content | replace({"\n":""}) }}
If your content also includes Windows lines endings use:
{{ content|replace({"\n":'', "\r":''}) }}
or just use the trim filter which internally uses the PHP trim function which will strip all sorts of whitespace from the beginning and end of a string:
{{ content |trim }}
Upvotes: 1