mindkomm / timber-integration-woocommerce

WooCommerce integration for Timber
MIT License
109 stars 20 forks source link

Autoloading .twig template ignores Woocommerce PHP overrides #29

Closed tomablan closed 10 months ago

tomablan commented 2 years ago

Hi, first thanks for your work.

I'm starting using your integration and I'm experimenting something confusing.

I'm using the 'if present, automatic loading / parsing template.twig file' feature, but I needed to change some basic php logic. I noticed that if i want to both override, for example woocommerce/single-product/add-to-cart/simple.php AND templates/woocommerce/single-product/add-to-cart/simple.twig, the twig template has the priority over the php and my woocommerce override would never be executed.

Am I the only on experiencing the situation ? And is it possible to :

I'm open to discuss, thank you !

gchtr commented 1 year ago

Hey @tomablan

I think I won’t change how this works. If you add a Twig file, it’s meant to replace the default WooCommerce logic instead of a PHP file.

It’s not possible for me to run the PHP file first and then render the Twig file. If you look at the code, you’ll see that I render the Twig file and then return an empty PHP file. WooCommerce will then include that file:

https://github.com/mindkomm/timber-integration-woocommerce/blob/345e711378cf89f156b5e7eaeaaf76f66c8725b0/lib/WooCommerce.php#L196-L202

So any logic that you would change in the PHP file would actually run after the Twig file. And I can’t tell WooCommerce to not run that logic.

But you have other ways to solve this:

  1. Change the logic in the Twig file.
  2. Change the logic in your PHP file and call Timber::render() with your Twig template.

single-product/add-to-cart/simple.php

<?php

// Some logic changing code.

Timber::render( 'woocommerce/single-product/add-to-cart/simple.twig' );

But I see that there’s no easy way to generate the context for that template file. I might have to add a function so you could do something like this:

<?php

// Some logic changing code.

Timber::render(
    'woocommerce/single-product/add-to-cart/simple.twig',
    // This function doesn’t exist yet.
    \Timber\Integration\WooCommerce::get_template_context()
);

To understand better whether this would be a good solution: Could you tell me more about the logic that you wanted to change in PHP? Maybe there’s even a simpler way to solve this.