Elementor自定义Widget如何实现嵌套Widget渲染?技术咨询
Elementor Widget嵌套渲染实现方案(Bootstrap Row/Col示例)
要实现自定义Row/Col Widget的嵌套渲染(类似Vue的slot或Rails的yield),核心是利用Elementor Widget基类内置的子元素渲染能力,以下是具体实现步骤:
1. 自定义Row Widget(支持嵌套子元素)
创建继承自\Elementor\Widget_Base的Row类,在渲染方法中调用render_children()输出子Widget:
class Custom_Row_Widget extends \Elementor\Widget_Base { public function get_name() { return 'custom_row'; } public function get_title() { return 'Custom Bootstrap Row'; } public function get_icon() { return 'eicon-columns'; } public function get_categories() { return [ 'basic' ]; } protected function _register_controls() { $this->start_controls_section( 'section_row_settings', [ 'label' => 'Row Settings', 'tab' => \Elementor\Controls_Manager::TAB_CONTENT ] ); // 可添加自定义控件:比如gutter间距、对齐方式等 $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); echo '<div class="row">'; // 渲染所有拖入Row的子元素(如Col Widget) $this->render_children(); echo '</div>'; } protected function _content_template() { ?> <div class="row"> <# view.renderChildren(); #> </div> <?php } }
2. 自定义Col Widget(支持内部嵌套内容)
同理创建Col类,同样通过render_children()渲染内部子元素:
class Custom_Col_Widget extends \Elementor\Widget_Base { public function get_name() { return 'custom_col'; } public function get_title() { return 'Custom Bootstrap Column'; } public function get_icon() { return 'eicon-column'; } public function get_categories() { return [ 'basic' ]; } protected function _register_controls() { $this->start_controls_section( 'section_col_settings', [ 'label' => 'Column Settings', 'tab' => \Elementor\Controls_Manager::TAB_CONTENT ] ); // 添加Bootstrap列宽选择控件 $this->add_control( 'col_width', [ 'label' => 'Column Width', 'type' => \Elementor\Controls_Manager::SELECT, 'options' => [ 'col-12' => 'Full Width', 'col-6' => 'Half Width', 'col-4' => 'One Third', 'col-3' => 'One Fourth', ], 'default' => 'col-12', ] ); $this->end_controls_section(); } protected function render() { $settings = $this->get_settings_for_display(); echo '<div class="' . esc_attr( $settings['col_width'] ) . '">'; // 渲染Col内部的子元素(文本、图片等其他Widget) $this->render_children(); echo '</div>'; } protected function _content_template() { ?> <div class="{{ settings.col_width }}"> <# view.renderChildren(); #> </div> <?php } }
3. 注册自定义Widget
将两个Widget注册到Elementor:
function register_bootstrap_grid_widgets() { \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Custom_Row_Widget() ); \Elementor\Plugin::instance()->widgets_manager->register_widget_type( new Custom_Col_Widget() ); } add_action( 'elementor/widgets/widgets_registered', 'register_bootstrap_grid_widgets' );
关键说明
render_children()(前端渲染)和view.renderChildren()(编辑模式模板)是Elementor实现子元素嵌套的核心方法,对应你提到的slot/yield机制,自动处理拖入的子Widget渲染。- 原生Elementor的Section/Column组件也是基于相同逻辑实现嵌套的,可参考官方源码(
elementor/includes/widgets/section.php、column.php)进一步扩展。 - 无需额外配置嵌套权限,只要在渲染时调用上述方法,Elementor会自动允许子Widget拖入。
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

