gutenberg icon indicating copy to clipboard operation
gutenberg copied to clipboard

iAPI: Implement a `data-wp-if` directive

Open DAreRodz opened this issue 1 year ago • 1 comments

What problem does this address?

For now, we haven't required a directive to render HTML conditionally. However, there are cases where it has proven to be useful, rather than using techniques like adding the attribute hidden to those elements that shouldn't be displayed.

Related discussion for a data-wp-show directive: https://github.com/WordPress/gutenberg/discussions/53058

What is your proposed solution?

The data-wp-if directive implementation was delayed, waiting for the WP HTML API to support adding inner elements natively rather than relying on the iAPI's custom logic. We could keep waiting for this feature to be implemented or make the necessary changes to WP_Interactivity_API_Directives_Processor to support this directive.

DAreRodz avatar Jul 23 '25 12:07 DAreRodz

I'd like to pick this up. Before starting, I want to check which direction the team prefers, since the original blocker still seems to apply.

Where things stand today

  • Client side, packages/interactivity/src/directives/ has no if directive yet.
  • Server side, WP_Interactivity_API in WordPress 7.2-beta1 registers data-wp-html and data-wp-each, but not data-wp-if.
  • As far as I can tell, WP_HTML_Processor still has no public method to set an element's inner HTML. The directives processor has its own helpers instead (set_content_between_balanced_tags(), append_content_after_template_tag_closer()), which data-wp-each already uses.

Possible approach

Follow the data-wp-each pattern: data-wp-if goes on a <template> element, and its content is rendered after the template when the condition is truthy, on the server through WP_Interactivity_API_Directives_Processor and on the client through a new if directive. This would avoid waiting on the HTML API, at the cost of more custom processor logic.

Questions

  1. Should this wait for native HTML API support, or is extending the directives processor acceptable now?
  2. Is a <template>-based directive the right shape, or should it work on regular elements?
  3. Any expectations for client-side navigation, or for hydrating content the server didn't render because the condition was false?

Since the server-side part lives in WordPress core, I'd open a Trac ticket and a wordpress-develop PR alongside the Gutenberg PR.

dhananjaykuber avatar Oct 23 '26 09:10 dhananjaykuber