Roots Discourse

Enqueue assets based on layout used

Hello everyone,

I need two different layouts. But also different assets (js/css) per layout.
How do I determine what layout is used, so I can write a condition.

If somebody can point me to a direction, it is much appreciated. Thanks!

The body class is used for this. You can write a CSS selector body.template-class and use it for routing in JavaScript (Sage 9 shipped a simple body-class router, but you can use any library for that or your own code).

Thank you for answering.

I’m affraid this is not the answer I’m looking for. Given solution still have all assets loaded, even if not used by specific layout.

I want a condition around wp_enqueue_style based on the layout used.

Then you have to also configure the sage setup so webpack emits separate files.
By default the main style and JavaScript file are both bundled together from all the individual, single files.

For conditionally enqueuing the scripts/styles, you can use so called conditional tags in the action handler function:

For WordPress:

For WooCommerce:

It may also useful to install a Debug plugin so you can exactly see the slug of the template currently used for a particular frontend URL.

Example (what I use for sage 9):

function register_styles_scripts() {

    wp_register_style( 'all-pages',    asset_path( 'styles/main.css'    ) );
    wp_register_style( 'blog-page',    asset_path( 'styles/blog.css'    ) );
    wp_register_style( 'contact-page', asset_path( 'styles/contact.css' ) );

add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\register_styles_scripts', 100 );

function enqueue_styles_scripts() {

    // all pages
    wp_enqueue_style( 'all-pages' );

    if( is_blog() ) {
        // blog page
        wp_enqueue_style( 'blog-page' );

    if( basename( get_page_template() ) === 'contact.blade.php' ) {
        // Contact form page
        wp_enqueue_style( 'contact-page' );

add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_styles_scripts', 100 );

For the admin/backend I just add all the editor styles (plus supplementary editor styles for editor-specific wrappers and quirks (Gutenberg)) because the backend isn’t really performance-optimized that way.

This is wat I intend to do. But then the condition, instead of is_blog() or ... === 'contact.blade.php, should be based on views/layouts/nameoflayout.blade.php`.

But I think that the condition can not be based on the layout, so it has to be on other conditions.

For those who want to know and my own future reference, I now based the condition on the value of \Roots\app('sage.view').

Thank you very much for your time.

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