php - 一个变量中的 PHP 包含另一个变量中的 HTML
问题描述
我想在 HTML 中添加一个变量,该变量包含另一个变量中的函数(无论是 WordPress 还是自定义函数)。问题是,当我连接它时,它会弹出前端的 div 容器之外,我需要它位于容器内部。
例如此处显示的示例,我希望在这些 div 中生成“$stay_put”或 PHP:
function sort_sections( $sections ) {
$sections = explode(',', $sections);
$output = '';
/* $stay put needs to be able to hold any function */
$stay_put = wp_list_pages();
if ( empty( $sections ) ) {
return $output;
}
foreach( $sections as $section ) {
switch ( $section ) {
case 'section_a':
$output .= '<div>Section A</div>';
break;
case 'section_b':
$output .= '<div>Section B</div>';
break;
default:
break;
}
}
return $output;
}
我想出但在容器外显示变量:
$stay_put
foreach( $sections as $section ) {
switch ( $section ) {
case 'section_a':
$output .= '<div>' . $stay_put . '</div>';
break;
case 'section_b':
$output .= '<div>' . $stay_put . '</div>';
break;
default:
break;
}
}
如果有人可以提供帮助,
先感谢您。
编辑:解决方案
function render_sections( $sections ) {
$sections = explode(',', $sections);
$output = '';
$stay_put = wp_list_pages(['echo' => false]);
if ( empty( $sections ) ) {
return $output;
}
foreach( $sections as $section ) {
switch ( $section ) {
case 'section_a':
$output .= '<div>Section A';
$output .= $stay_put;
$output .= '</div>';
break;
case 'section_b':
$output .= '<div>Section B';
$output .= $stay_put;
$output .= '</div>';
break;
default:
break;
}
}
return $output;
}
解决方案
您的示例代码的主要问题是您想要返回输出,但调用wp_list_pages
不会返回所需的信息,而是直接回显它。如果要将结果添加wp_list_pages
到输出中,则必须将参数添加到wp_list_pages
. 根据wordpress 文档,您必须设置echo
为false
.
在每个部分的 div 之后添加它,请参见以下代码:
function render_sections( $sections ) {
$sections = explode(',', $sections);
$output = '';
$stay_put = wp_list_pages(['echo' => false);
if ( empty( $sections ) ) {
return $output;
}
foreach( $sections as $section ) {
switch ( $section ) {
case 'section_a':
$output .= "<div>Section A</div>';
$output .= $stay_put;
break;
case 'section_b':
$output .= '<div>Section B</div>';
$output .= $stay_put;
break;
default:
break;
}
}
return $output;
}
请注意,我已将函数名称从更改为sort_sections
,render_sections
因为这似乎更准确地描述了它的功能(干净的代码)。
推荐阅读
- python - 为什么模型的图层形状是 (1000,) 而不是 Keras 中的 (1000)?
- php - 让 JW Player 响应式
- c# - 如何在 DynamicMethod 中调用 DynamicMethod
- laravel - 属性'开始'未定义的vuejs laravel
- python - Django 网站部署到 heroku。应用程序错误
- python - 为什么这个批处理脚本没有启动我的 python 程序?
- java - 有没有办法让我的前台服务不间断地运行。当最小化窗口中的Cross(X)按钮清除手机缓存时它会停止吗?
- regex - 正则表达式匹配一个单词并忽略该行,如果它包含另一个单词
- r - 如何创建一个返回两个整数之和的函数?
- ios - 导航栏后退按钮不显示?