wordpresswordpress-gutenberg

How can I display my attributes in view.js? [@wordpress/create-block]


I'm new to wordpress and i tried the command to generate a wordpress/block

npx @wordpress/create-block wis-slider --no-plugin

In this folder i get a "view.js" were i can load external libraries like swiper.js

Unfortunately, i do not know how to display the block attributes in view.js?


Solution

  • Very simple way to get attributes in view.js is to pass as varibales in save.js like this using JSON.stringnify() (code line: { var testimonialsSlides=${ JSON.stringify(slides) } } ):

    export default function Save({ attributes }) {
    const { title, slides } = attributes;
    
    const {blockClassName, blockStyleObject } = useBlockStyle( 'testimonials', {
        color: attributes.color,
        bgColor: attributes.bgColor,
    } );
    
    const blockProps = useBlockProps.save({
        className: `${blockClassName} ${blockClassName}-${ attributes.clientId }`,
        style: blockStyleObject
    });
    
    return (
        <div {...blockProps}>
            <div className={`${blockClassName}__icon`}></div>
            <RichText.Content value={ title  } tagName="p" className={`${blockClassName}__title`} />
    
            <div className={`swiper ${blockClassName}__swiper`}>
                <div className="swiper-wrapper">
                    {slides.map(( slide, index  ) => (
                        <div className={ `swiper-slide ${ index === 0 ? 'swiper-slide-active' : '' }` }>
                            <div  className="wp-block-oimocode-testimonials__item">
                                <div className="wp-block-oimocode-testimonials__rating">
                                    <FontAwesomeIcon icon={faStar} />
                                    <FontAwesomeIcon icon={faStar} />
                                    <FontAwesomeIcon icon={faStar} />
                                    <FontAwesomeIcon icon={faStar} />
                                    <FontAwesomeIcon icon={faStar} />
                                </div>
                                <RichText.Content value={ slide.content } tagName="p" className={`${blockClassName}__review`} />
                            </div>
                        </div>
                    ))}
                </div>
                <div className="swiper-pagination">
                    {slides.map(( slide, index  ) => (
                        <span className={ `swiper-pagination-bullet ${ index === 0 ? 'swiper-pagination-bullet-active' : '' }` }>
                            { slide.imgUrl && <img src={ slide.imgUrl } alt={ `reviewer-avatar-${ index }` } />}
                            { ! slide.imgUrl && <FontAwesomeIcon icon={faUser} /> }
                        </span>
                    ))}
                </div>
            </div>
            <script>{ `var testimonialsSlides=${ JSON.stringify(slides) }` }</script>
        </div>
    );
    

    }