Interactivity

WordPress Content In Islands

TemplateX server tags can live inside Svelte islands, so browser state can control markup without moving WordPress data into JavaScript.

Put A Query Inside Svelte State#

Use Svelte around TemplateX server content when the browser only needs to control visibility:

php
<script>  let showPosts = true;</script><section class="posts">  {#if showPosts}    {{ query:posts limit="3" }}      <article>        <h2><a href="{{ url }}">{{ title }}</a></h2>      </article>    {{ else }}      <p>No posts found.</p>    {{ /query:posts }}  {/if}</section>

The showPosts condition runs in Svelte. The query still runs in WordPress, and {{ title }} and {{ url }} are still TemplateX values from the current post.

Use Server Values In Attributes#

Server-rendered values can appear in attributes inside Svelte markup:

php
<script>  let selected = false;</script><a href="{{ url }}" data-title="{{ title }}" class:active={selected}>  {{ title }}</a>

TemplateX renders the URL and title with PHP, then Svelte owns the class:active state.

Let Server Tags Wrap Svelte#

Server tags can decide whether an island is printed:

php
<script>  let count = 0;</script>{{ if title }}  <button type="button" onclick={() => count++}>{count}</button>{{ else }}  <button type="button" onclick={() => count--}>{count}</button>{{ /if }}

The title condition runs on the server. Each branch that contains Svelte markup gets the island it needs.

Query empty states can do the same:

php
<script>  let retries = 0;</script>{{ query:posts limit="3" }}  <article>{{ title }}</article>{{ else }}  <button type="button" onclick={() => retries++}>Retry {retries}</button>{{ /query:posts }}

The posts render on the server. The retry button is interactive only when WordPress prints the empty branch.

Use Partials And Components#

TemplateX partials can render inside Svelte markup:

php
<script>  let visible = true;</script>{#if visible}  {{ partial:card label="Featured" }}{/if}

Known component-style partial tags are server-rendered too:

php
<script>  let visible = true;</script>{#if visible}  <Rating rating="{{ rating }}" />{/if}

<Rating /> maps to resources/views/partials/rating.php when that partial exists.

If a capitalized tag is not a known TemplateX partial, TemplateX leaves it for Svelte. That lets imported Svelte components work:

php
<script>  import Badge from './Badge.svelte';  let visible = true;</script>{#if visible}  <Badge label="New" />{/if}