Using ajax/wp_localize_script with Roots/bundle in Sage 10

Hi, I just want to know how to pass the parameters to the .js file using the Roots/bundle. In the previous tag of roots sage 10 to pass the parameter to the specific .js file we can use:

wp_localize_script( 'sage/blog.js', 'ajax_posts', [
            'ajaxurl' => admin_url( 'admin-ajax.php' ), // WordPress AJAX
            'posts' => json_encode( $wp_query->query_vars ),
            'current_page' => get_query_var( 'paged' ) ? get_query_var('paged') : 1,
            'max_page' => $wp_query->max_num_pages,
            'nonce' => wp_create_nonce('ajax-nonce'),
        ]);

But how we can achieve this using the Roots/bundle. In the latest update of sage 10 they used bundle('app')->enqueue(); to enqueue the js file but how we can use the localize_script using this bundle?

Sorry for my bad english.

We need to update our docs to reflect the changes made to enqueuing assets when we switched over to using Bud earlier this week, but…

wp_localize_script needs to reference the handle of the enqueued asset. As of right now, app.js is built and enqueued with the handle app/1. To add a JS object to the app bundle, you’d do:

wp_localize_script('app/1', 'example', ['hello' => 'world']);

The result:

<script id='app/1-js-extra'>
var example = {"hello":"world"};
</script>
<script src='http://example.test/app/themes/sage/public/app.8bd132.js' id='app/1-js'></script>
2 Likes

As of Acorn v2 beta 5 (which was just merged into Sage), you can do this:

add_action('wp_enqueue_scripts', function () {
    bundle('app')->enqueue()->localize('example', ['hello' => 'world']);
}, 100);

Code references from Acorn:

Props @QWp6t!

7 Likes

This is awesome. Thank you @ben <3

This topic was automatically closed after 42 days. New replies are no longer allowed.