在drupal中,我们可以通过API接口向前端提供数据,也可以将数据放入drupalSettings中,有前端通过JS获取数据。即通过预处理函数在数据传递给主题模板之前进行增加或修改数据。
官方文档参考:
预处理函数
方案1:
/**
* Implements hook_preprocess_page().
*/
function ixtend_report_preprocess_page(array &$variables) {
//1. 条件判断
//2. 数据获取
$requested_vaials_diagnosis = ...
$requested_month = ...
//3. 赋值
$variables['#attached']['library'][] = 'ixtend_report/ixtend_report-js';
$variables['#attached']['drupalSettings']['ixtend_report']['chart_data'] = json_encode([
'requested_vaials_diagnosis' => $requested_vaials_diagnosis,
'requested_month' => $requested_month
]);
}
方案2:
/**
* Implements hook_page_attachments().
*/
function ixtend_report_page_attachments(array &$attachments){
//1. 条件判断
//2. 数据获取
$requested_vaials_diagnosis = ...
$requested_month = ...
//3. 赋值
$attachments['#attached']['library'][] = 'ixtend_report/guest';
$attachments['#attached']['drupalSettings']['ixtend_report']['chart_data'] = [
'requested_vaials_diagnosis' => $requested_vaials_diagnosis,
'requested_month' => $requested_month
];
}
ps:打开相应页面,在浏览器控制台(console)中输入drupalSettings后回车即可看到drupalSettings下的数据。