freshflesh/wp-render-template-part

是本地作用域传递参数的原生 WP 函数 `get_template_part` 的替代方案

1.1.2 2017-01-05 14:44 UTC

This package is not auto-updated.

Last update: 2024-09-14 19:31:16 UTC


README

是原生 WordPress 函数 get_template_part() 的替代方案,可以传递参数到局部作用域。

安装

  • 使用 composer : composer require freshflesh/wp-render-template-part
  • 或者手动下载并包含 src/wp-render-template-part.php 文件

##参数

  • $slug: (string) (必填) 通用模板的 slug 名称。
  • $name: (string) (可选) 专用模板的名称。默认值:null
  • $args: (array) (可选) 包含传递给模板的参数的关联数组。默认为空数组。
  • $echo: (boolean) (可选) 是否输出或返回渲染的模板。默认为 true。

用法

要向模板部分传递参数,请使用 render_template_part() 函数。

简单示例

父模板

<?php
    $args =  array(
                'title'   => 'Hello there.',
                'content' => 'Lorem ipsum sid amet'
             );
             
    render_template_part( 'block', 'widget', $args );

子模板

<div class="widget">
    <h2><?php echo $title; // will output 'Hello there.' ?></h2>
    <p><?php echo $content;  // will output 'Lorem ipsum sid amet' ?></p>
</div>

返回值示例

例如,当通过 AJAX 返回模板时非常有用

<?php
    // get rendered template
    $html = render_template_part( 'partials/sidebar', 'article', array(
                 'post_id' => $post->ID
            ) );
    // send in json response 
    wp_send_json_success( array( $html );

特性

WP_Query 自动加载

将 WP_Query 实例作为 query 参数传递时,会自动将其设置为当前循环。

WP_Post 自动加载

将 WP_Post 实例作为 post_object 参数传递时,会自动调用 setup_post_data(),这样您就可以开始使用 the_title()the_content() 等。

注意:因此,querypost_object 是保留参数名称

可扩展性

提供了 2 个钩子以扩展其行为

动作: do_action( "render_template_part_{$slug}", $slug, $name, $args, $echo );

过滤器: $args = apply_filters( "render_template_part_{$slug}_args", $args, $slug, $name, $echo );