我不能在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);
答案 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);