Skip to content

Twig Templates

WPBits Block Studio supports Twig templates for dynamic block rendering. Twig is a PHP template engine that offers security features, caching, and an easy-to-read syntax.

Twig provides several advantages over plain PHP templates:

  • Security — Automatic escaping prevents XSS attacks
  • Readability — Clean, simple syntax
  • Caching — Compiled templates are cached for performance
  • Extensibility — Filters and functions for common tasks

A simple block template in Twig:

{# block-title.twig #}
<div class="feature-block">
<h2>{{ attributes.title }}</h2>
<p>{{ attributes.description }}</p>
</div>

Twig automatically escapes output to prevent XSS:

{# This is safe - content is escaped #}
{{ attributes.title }}
{# For raw HTML (use carefully) #}
{{ attributes.content | raw }}

Access block attributes with dot notation:

{{ attributes.title }}
{{ attributes.image.url }}
{{ attributes.settings.size }}
{% if attributes.show_icon %}
<span class="icon">{{ attributes.icon }}</span>
{% endif %}
{% for item in attributes.items %}
<li>{{ item.name }}</li>
{% endfor %}

Transform output with filters:

{# Uppercase #}
{{ attributes.title | upper }}
{# Date formatting #}
{{ attributes.date | date('F j, Y') }}
{# Truncate #}
{{ attributes.text | truncate(100) }}

WPBits Block Studio’s Twig implementation includes:

  • All output is escaped by default
  • Sandboxed environment
  • Restricted functions
FilterDescriptionExample
upperUppercase{{ text | upper }}
lowerLowercase{{ text | lower }}
trimRemove whitespace{{ text | trim }}
dateFormat date{{ date | date('Y-m-d') }}
esc_htmlEscape HTML{{ html | esc_html }}
esc_attrEscape attribute{{ attr | esc_attr }}
FunctionDescription
asset()Get asset URL
theme()Get theme URL

WPBits Block Studio generates these template files:

Twig template for primary rendering:

<div class="my-block">
<h2>{{ attributes.title }}</h2>
</div>

Template for editor preview (if different from frontend):

<div class="my-block preview">
<h2>{{ attributes.title }}</h2>
</div>
  1. In block editor, go to Template tab
  2. Select Twig as render mode
  3. Choose template type

Create your template using Twig syntax:

<div class="testimonial-block">
{% if attributes.quote %}
<blockquote>{{ attributes.quote }}</blockquote>
{% endif %}
{% if attributes.author %}
<cite>{{ attributes.author }}</cite>
{% endif %}
{% if attributes.rating %}
<div class="rating">
{% for i in 1..attributes.rating %}
{% endfor %}
</div>
{% endif %}
</div>

WPBits Block Studio shows a live preview as you edit the template.

  1. Check file permissions
  2. Verify Twig files are in correct location
  3. Enable WP Debug to see errors

Use | raw only when absolutely necessary, and never with user input:

{# Safe - user input is escaped #}
{{ attributes.user_content }}
{# Dangerous - only use with trusted content #}
{{ trusted_html_content | raw }}