首页 > 解决方案 > 使用 AJAX 重新加载 .twig 模板

问题描述

我将https://github.com/gmrchk/swup与 Twig/Timber 结合使用。它很好用,但是,我意识到每当我进入新页面时,我的 if 子句都不起作用,因为 SWUP 无法从我的 twig 文件中读取 if 参数。(它是一个动态加载页面的 JS 库)

例如:

{% if fn('is_single') %}
<div class="progress"></div>
{% endif %}

当我最初在非单一帖子页面上加载页面时,根本不会加载。

我的想法是使用 AJAX 调用重新渲染 header.twig(上面提到的 if 子句所在的位置)。

AJAX 调用如下所示:

function swupReplaceHeader() {
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'spx_replace_header',
        },
        success: function (output) {
            console.log(output);
        }
    });
}

swupReplaceHeader();
document.addEventListener('swup:clickLink', swupReplaceHeader);

它被包裹在一个事件监听器中,每次我点击一个链接时都会触发它。

WP 函数如下所示:

add_action('wp_ajax_spx_replace_header', 'spx_replace_header');
add_action('wp_ajax_nopriv_spx_replace_header', 'spx_replace_header');
function spx_replace_header()
{
    $context = Timber::get_context();
    Timber::render('templates/header.twig', $context);
    wp_send_json_success(['AJAX is working']);
}

我添加了发送 JSON 消息来测试我的 AJAX 调用是否正常工作。

现在,每当我在没有 Timber 代码的情况下测试 AJAX 调用时,它都在工作,但是当我将两条 Timber 行添加到函数中时,什么也没有发生 - 甚至 JSON 消息都没有出现。我也试过 Timber::compile 没有任何运气。

我希望有一个人可以帮助我..

最好的,丹尼斯

标签: ajaxwordpresstwigtimber

解决方案


aj-adl 在Github上发布的答案:

嘿丹尼斯,

你正在调用 wp-admin/admin-ajax.php,所以像 is_ajax() 这样的条件会返回 true,但 is_single() 肯定不会。

请记住,PHP 在每个请求结束时关闭,丢弃状态等,因此对 admin-ajax.php 脚本的调用是一个完全隔离的进程,与为页面提供初始标记的进程完全隔离,并且不知道是什么从等处调用它的页面

出于这个原因,您需要传入条件所需的任何数据,可能作为查询字符串参数。

PHP:

add_action('wp_ajax_nopriv_spx_replace_header', 'spx_replace_header');

function spx_safe_get_string( $key )
{
    if ( ! isset( $_GET[ $key ] ) ) return '';
   return sanitize_text_field( $_GET[ $key ] );
}

function spx_replace_header()
{
    $context = Timber::get_context();
    // Set this in the context, so we can access it in our twig file easily
    $context[ 'type' ] = spx_safe_get( 'my_page_type' );
    Timber::render('templates/header.twig', $context);
}

JS:

window.addEventListener('load', function() {
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: {
            action: 'spx_replace_header',
            my_page_type: 'single',
        },
        success: function (data) {
            console.log(data);
        }
    });
})

枝条:

{% embed "objects/header.twig" with {'hamburger': 'hamburger--spring'} %}
{% endembed %}

{% if type == 'single' %}
    <div class="progress"></div>
{% endif %}

{% embed "objects/header.twig" with {'id': '--sticky', 'hamburger': 'hamburger--spring'} %}
{% endembed %}

推荐阅读