用AJAX重新加载.twig模板

时间:2019-05-10 18:28:28

标签: ajax wordpress twig timber

我将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,但是没有运气。

我希望有人能帮助我。

最好, 丹尼斯

1 个答案:

答案 0 :(得分:1)

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 %}