Skip to content

Advanced Features

semihalev edited this page Mar 11, 2025 · 2 revisions

Advanced Features

Template Compilation

For maximum performance in production environments, Twig supports compiling templates to a binary format:

Benefits of Template Compilation

  1. Faster Rendering: Pre-compiled templates skip the parsing step, leading to faster rendering
  2. Reduced Memory Usage: Compiled templates can be more memory-efficient
  3. Better Deployment Options: Compile during build and distribute only compiled templates
  4. No Source Required: Run without needing access to the original template files

Using Compiled Templates

// Create a new engine
engine := twig.New()

// Compile a template
template, _ := engine.Load("template_name")
compiled, _ := template.Compile()

// Serialize to binary data
data, _ := twig.SerializeCompiledTemplate(compiled)

// Save to disk or transmit elsewhere...
ioutil.WriteFile("template.compiled", data, 0644)

// In production, load the compiled template
compiledData, _ := ioutil.ReadFile("template.compiled")
engine.LoadFromCompiledData(compiledData)

Compiled Template Loader

A dedicated CompiledLoader provides easy handling of compiled templates:

// Create a loader for compiled templates
loader := twig.NewCompiledLoader("./compiled_templates")

// Compile all templates in the engine
loader.CompileAll(engine)

// In production
loader.LoadAll(engine)

String Escape Sequences

Twig supports standard string escape sequences to include special characters in string literals:

{{ "Line with \n a newline character" }}
{{ "Quotes need escaping: \"quoted text\"" }}
{{ "Use \\ for a literal backslash" }}
{{ "Escape Twig syntax: \{\{ this is not a variable \}\}" }}

The following escape sequences are supported:

  • \n: Newline
  • \r: Carriage return
  • \t: Tab
  • \": Double quote
  • \': Single quote
  • \\: Backslash
  • \{: Left curly brace (to avoid being interpreted as Twig syntax)
  • \}: Right curly brace (to avoid being interpreted as Twig syntax)

This is particularly useful in JavaScript blocks or when you need to include literal braces in your output.

Whitespace Handling

Twig templates can have significant whitespace that affects the rendered output. The implementation supports the following mechanism for controlling whitespace:

Apply Tag

The apply tag allows you to apply a filter to an entire block of template content:

{% apply upper %}
    This text will be converted to uppercase.
    {{ variable }} will also be uppercase.
{% endapply %}

This is particularly useful for:

  • Applying transformations to both static and dynamic content
  • Handling complex HTML with the spaceless filter
  • Creating consistent text formatting across multiple lines
  • Processing content with custom filters

Example usages:

{# Remove whitespace between HTML tags #}
{% apply spaceless %}
    <div>
        <strong>Hello</strong>
    </div>
{% endapply %}

{# Result: <div><strong>Hello</strong></div> #}

{# Convert content to uppercase #}
{% apply upper %}
    Welcome, {{ user.name }}\!
{% endapply %}

{# Replace content #}
{% apply replace('e', 'a') %}
    Hello there
{% endapply %}
{# Result: Hallo thara #}

Verbatim Tag

The verbatim tag allows you to output Twig syntax without it being processed:

{% verbatim %}
    This {{ will not be processed }} as a variable.
    {% if statements won't be executed %}
{% endverbatim %}

This is useful when:

  • Displaying Twig syntax as part of documentation
  • Including template examples in your output
  • Working with JavaScript frameworks that use similar syntax (Vue.js, Angular, etc.)
  • Creating code examples that include Twig syntax

Whitespace Control

The whitespace control modifiers (- character) allow you to trim whitespace around tags:

<div>
    {{- greeting -}}     {# Removes whitespace before and after #}
</div>

Using these modifiers:

  • {{- ... }}: Removes whitespace before the variable output
  • {{ ... -}}: Removes whitespace after the variable output
  • {{- ... -}}: Removes whitespace both before and after
  • {%- ... %}: Removes whitespace before the block tag
  • {% ... -%}: Removes whitespace after the block tag
  • {%- ... -%}: Removes whitespace both before and after

This feature helps you create cleaner output, especially when generating HTML with proper indentation in templates but needing compact output for production.

See the Whitespace Control wiki page for more detailed examples and best practices.

Compatibility

This implementation aims to be compatible with Twig PHP version 3.x syntax and features. While we strive for full compatibility, there may be some minor differences due to the nature of the Go language compared to PHP.

Security Considerations

When using Twig or any template engine:

  • Never allow untrusted users to modify or create templates directly
  • Be cautious with user-provided variables in templates
  • Consider using the HTML escaping filters (escape or e) for user-provided content
  • Use sandbox mode when including templates from potentially untrusted sources
  • In sandbox mode, carefully configure security policies to restrict dangerous operations

See the Sandbox Mode wiki page for more information on secure template evaluation.

Clone this wiki locally