Interactivity

State And Events

State and events are the smallest useful piece of TemplateX interactivity: a value changes in the browser and the markup reacts without a page reload.

Start With A Counter#

Put a plain <script> block in the view and use the state in the markup:

phpresources/views/front-page.php
<script>  let count = 0;</script><button type="button" onclick="{{ count += 1 }}">Add</button><p>{{ count }}</p>

count is browser-side state. Because the event expression updates it, TemplateX turns the plain let count = 0 into Svelte state in the generated component.

onclick="{{ count += 1 }}" is TemplateX's event shorthand. It compiles to a Svelte click handler.

{{ count }} prints the current browser value. It is a value tag, not a paired tag, so it has no closing tag.

Use A Function#

Move behavior into a function when the event does more than one small assignment:

php
<script>  let count = 0;  function add() {    count += 1;  }</script><button type="button" onclick="{{ add }}">Add</button><p>{count}</p>

onclick="{{ add }}" references the function from the script block. {count} is native Svelte output, so TemplateX knows the surrounding markup belongs to the generated island.

Call A Function With Arguments#

Event shorthands can call functions and pass values:

php
<script>  let activeTab = 'profile';  function select(tab) {    activeTab = tab;  }</script><button type="button" onclick="{{ select('profile') }}">Profile</button><button type="button" onclick="{{ select('settings') }}">Settings</button><p>{activeTab}</p>

TemplateX wraps expression-style handlers for you, so the generated Svelte handler runs on click instead of during render.

Use Native Svelte Events#

You can also write the Svelte event handler directly:

php
<script>  let count = 0;</script><button type="button" onclick={() => count += 1}>Add</button><p>{count}</p>

Use whichever shape is clearer for the view. The TemplateX shorthand is compact for simple handlers. Native Svelte syntax is often clearer for inline arrow functions.

Hover Events#

onhover="{{ ... }}" is supported as a convenience alias:

php
<button type="button" onhover="{{ console.log('preview') }}">  Preview</button>

It compiles to a mouseenter handler.