iAPI: Implement a `data-wp-if` directive
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.
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 noifdirective yet. - Server side,
WP_Interactivity_APIin WordPress 7.2-beta1 registersdata-wp-htmlanddata-wp-each, but notdata-wp-if. - As far as I can tell,
WP_HTML_Processorstill 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()), whichdata-wp-eachalready 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
- Should this wait for native HTML API support, or is extending the directives processor acceptable now?
- Is a
<template>-based directive the right shape, or should it work on regular elements? - 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.