pp-bind-spread

The pp-bind-spread attribute allows you to dynamically apply multiple props as HTML attributes to a tag. It is ideal for cases where attributes like src, alt, width, height, or even class need to be set dynamically and in bulk.

Use Cases

Spread bindings are useful when dealing with components or elements that share multiple properties from different sources, such as dynamic image settings, style configurations, or accessibility props. It keeps templates cleaner and makes prop management more declarative.

Syntax

  • pp-bind-spread="propName": Applies all properties of the object propName as attributes.
  • pp-bind-spread="prop1, prop2": Merges multiple objects in order (left to right) and spreads their attributes into the element. Properties from later objects overwrite earlier ones.

Behavior

  • If a value is false, null, or undefined, the corresponding attribute will be removed.
  • If an attribute is already manually written in the HTML and was not previously spread, it will not be overwritten by pp-bind-spread.
  • Objects are merged in the order specified. Later props can overwrite earlier values.
  • Values are stringified automatically. If the value is an object, it is converted to a JSON string.

Example Usage

<img pp-bind-spread="imageProps" />

<img pp-bind-spread="defaultSettings, userOverrides" />

<script>
  pphp.state('imageProps', {
    src: 'https://example.com/logo.png',
    alt: 'Logo Image',
    width: 200,
    height: 200,
    class: 'rounded-lg shadow-lg'
  });

  pphp.state('defaultSettings', {
    class: 'rounded-md',
    width: 100
  });

  pphp.state('userOverrides', {
    width: 300,
    height: 150,
    class: 'rounded-full'
  });
</script>

In the above examples, all key-value pairs from the specified objects are dynamically applied as attributes to the element. You can mix and match multiple sources, and the latest source has higher priority.