如何在yii2中的registerJS()javascript代码中使用foreach php代码?

时间:2017-05-19 08:26:33

标签: javascript php yii2

我不能在yii2中的registerJS的javascript代码中使用foreach php代码。浏览器显示" PHP解析错误 - yii \ base \ ErrorException语法错误,意外' foreach' (T_FOREACH)"错误。这是我的代码:

<canvas id="bar-chart" width="500" height="150"></canvas>

<?php 
$lang = Yii::$app->language;
$title = 'title_'.$lang;

$this->registerJs("
                new Chart(document.getElementById('bar-chart'), {
                type: 'bar',
                data: {
                  labels: [
                                " . foreach ($models as $model) { . "
                                    ' " . $model->$title . " ',
                               " . } . "
                           ],
                  datasets: [
                    {
                      label:'Label',
                      backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'],
                      data: [479,1654,499, 2632]
                    }
                  ]
                },
                options: {
                  legend: { display: false },
                  title: {
                    display: true,
                    text: 'Title'
                  }
                }
            });
    ", yii\web\View::POS_READY);

2 个答案:

答案 0 :(得分:0)

我将从javascript输出中提取foreach代码。

CustomersMService

答案 1 :(得分:0)

您不能在字符串中间使用foreach语句。您应该事先生成来自foreach的字符串,然后将其与js字符串连接:

$mystring = "";
foreach ($models as $model) { 
  $mystring .= "' " . $model->$title . " ',";
}

$this->registerJs("
                new Chart(document.getElementById('bar-chart'), {
                type: 'bar',
                data: {
                  labels: [ $mystring ],
                  datasets: [
                    {
                      label:'Label',
                      backgroundColor: ['#3e95cd', '#8e5ea2','#3cba9f', '#e7fc00'],
                      data: [479,1654,499, 2632]
                    }
                  ]
                },
                options: {
                  legend: { display: false },
                  title: {
                    display: true,
                    text: 'Title'
                  }
                }
            });
    ", yii\web\View::POS_READY);