从Twig调用控制器



我目前正在发现symfony,我在一个控制器中调用一个函数时遇到了一些麻烦。

> class CsvController extends Controller {
public function generateCsvAction(){
    $conn=$this->get('database_connection')
    $results=$conn->query("
    SELECT *
    FROM external_attribute;
    ")
    $response=new StreamedResponse();
    $response->setCallback(function() use($results)){
        $handle=fopen("/home/basile/Documents/backend/src/CampaignBundle/Controller/test.csv","w+");
        fputcsv($handle,array('test1
            test2,
            test3,
            test4,
            test5,
            test6,
            test7,
            test8')
        ),';');
    }
    fclose($handle);
}
$response->setStatusCode(200);
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition','attachment; filename="test.csv"');      
return $response;  

}

我已经在我的路由中设置了所有内容:

export_csv:
defaults: { _controller: CampaignBundle:Controller:CsvController.php }

现在,我想从名为" index.html.twig"的文件中的按钮中调用它。我知道我们可以从控制器渲染一些变量和数组,但是在这里我直接想调用函数

如果您有任何想法,它将非常受欢迎!

直接从模板中调用控制器:

{{ render(controller(
    'NameOfYourBundle:NameOfYourClass:NameOfYourFunction'
)) }}

如果控制器需要参数(例如(:

{{ render(controller(
    'NameOfYourBundle:NameOfYourClass:NameOfYourFunction', { 'id': 3 }
)) }}

您可以直接从视图中执行函数:

{% render "YourBundle:Csv:generateCsv" with { 'url': 'export_csv' } %}

JS和Ajax:

$("#button").on('click', function() { 
 $.ajax({
    url: {{render(controller("YourBundle:Csv:generateCsv")) }},
    success: function(result){
    ...
 }});
});

最新更新