cearls / timberland

A modern WordPress theme using Timber, Advanced Custom Fields Pro, Vite, Tailwind and Alpine.js
MIT License
78 stars 19 forks source link

How can I pass value from Twig template to block scoped script file and run block scoped scripts only when block exist? #24

Closed RichForever closed 12 months ago

RichForever commented 1 year ago

I am wondering is there any way to pass data from Twig file to the .js file inside block directory? For example, I have something like this in blocks directory

Inside index.twig I have data that I want to pass to the script.js file. It can be block id for example. Is there any way to do it? For now I added

<script> const blockId = {{ block.id|json_encode }} </script>

in index.twig and I can access it inside script.js file. The problem is when I don't have this block on the page. Somehow script.js file from block directory are trying to run. So actually I have 2 questions:

  1. Is there any way to proper pass data to the .js file in the block directory
  2. Is there any way to run scripts inside script.js file only when the block exist?
cearls commented 1 year ago

Hi, I would use Alpine.data and $refs to accomplish this.

For example:

<div x-data="sample">
    <h2 x-ref="heading"></h2>
</div>

<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('sample', () => ({
        init() {
           console.log(this.$refs.heading)
        }
    }))
})
</script>

As for running scripts only when the block exits, there isn't currently a way. But, I'm looking into using something like is-land.

https://is-land.11ty.dev/