SOLVED: Is there a way to add AlpineJS directive attributes?

I’m just trying to find a way to add AlpineJS directives to elements. I’ve tried adding them as regular attributes but Bricks strips out the colon.

I really want to be able to add things like this :

<button x-on:click="open = ! open">Toggle</button>

<div x-show="open"> ... </div>

I would be super useful for creating your own accessible components.

Has anyone tried and/or succeeded implementing Alpine?

Hi Brian,

Welcome to the forum!

Which version of Bricks are you using?

Thanks Sridhar! I’m using 1.5 beta.

Let me give a help.
Bricks will use WordPress sanitize_title to clean the custom attribute keys before rendering.

You could use sanitize_title filter to put possible alpine attributes into exclude list.

Example:

add_filter( 'sanitize_title', 'do_not_sanitize_alpine_attr', 10, 3);

function do_not_sanitize_alpine_attr($title, $raw_title, $context ) {

  // List out all possible attributes you may put on the custom attributes

  $alpine_attributes = ['x-on', 'x-data', 'x-show'];

  // Use PHP array_filter to check if the current sanitizing $raw_text is one of $alpine_attributes  

  $match = array_filter( $alpine_attributes, function( $value ) use ( $raw_title ) {

    return (strpos($raw_title, $value) !== false) ;

  } );

  // If array_filter result is not empty, then do not filter it. Return the original $raw_title

  if( !empty($match) ) {

    return $raw_title;

  }

  return $title;

}

You should put in more conditions like only if current page is homepage etc., to avoid your logic accidently allowed unwanted string being escape in other places.

Good luck.

3 Likes

Thanks so much Jenn, it works like a charm. You made my day! :grinning:

1 Like