Symfony 2:强制Twig使用换行符


Symfony 2: Force Twig to use line breaks

我正在开发一个Symfony 2应用程序,该应用程序应该创建一个CSV文件供下载:

sep=;
{% for header in headers %}{{ header|trans({}, 'app') }};{% endfor %}
{% for row in data %}
    {% for column in row %}{{ column }};{% endfor %}
{% endfor %}

控制器:

...
$response = new Response();
$response->headers->set('Content-Type', 'text/csv; charset=UTF-16LE');
$response->headers->set('Content-Disposition', 'attachment;filename="PaymentList.csv"');
$variables = array(
    'headers' => $headers,
    'data' => $data,
);
// Use UTF-16LE with BOM to be compatible with Excel on Win and Mac
$content = $this->renderView('AppBundle:Shop:export.csv.twig', $variables);
$content = chr(255) . chr(254) . mb_convert_encoding($content, 'UTF-16LE', 'UTF-8');
$response->setContent($content);
return $response;

这工作得很好,CSV文件可以在Windows和Mac OS X上的Excel中使用。但是,该文件也应该在一个相当旧的会计工具中使用,该工具需要'r'n换行,而Twig会产生'n换行。

有什么方法可以告诉Twig使用'r'n吗?

当然,在呈现视图后,我可以简单地在PHP中搜索/替换换行符。另一个解决方案是,完全用PHP创建CSV数据,而不涉及Twig。

这两种解决方案都是可行的,但我的观点不太明确。我想控制输出,这是由Twig创建的。这可能吗?

Twig将行结尾规范化为,请参阅此处的Github问题:https://github.com/twigphp/Twig/issues/1481

如前所述,如果您想使用Twig生成此输出,则需要扩展默认lexer,或者手动替换输出中的结尾。

行尾依赖于模板行尾。但是,如果模板"存储"在VCS中,它可能会被转换,而无需您的直接控制。

日期:https://www.designopsy.com/symfony2-export-csv/我发现了这样的东西:

  $response = new StreamedResponse();
  $response->setCallback(function(){
      $handle = fopen('php://output', 'w+');
      // Add the header of the CSV file
      fputcsv($handle, array('Name', 'Surname', 'Age', 'Sex'),';');
      // Query data from database
      $results = $this->connection->query( "Replace this with your query" );
      // Add the data queried from database
      while( $row = $results->fetch() )
      {
          fputcsv(
              $handle, // The file pointer
              array($row['name'], $row['surname'], $row['age'], $row['sex']), // The fields
          ';' // The delimiter
           );
      }
      fclose($handle);
  });