STCMS Documentation

Complete guide to building modern, secure React/PHP applications with STCMS framework

Using PHP Logic & Data in Twig Templates

A key part of building a dynamic website is passing data from your PHP backend to your Twig frontend. STCMS follows a core principle: **separation of concerns**. PHP handles the logic (fetching data, calculations), and Twig handles the presentation (displaying the data).

You should never write raw PHP inside your .twig files. Instead, here are the two recommended methods for making your PHP logic available to your templates.


Method 1: Passing Page-Specific Data

This is the standard approach for data that is only needed by one specific page. The logic should be placed inside the core router file, which is responsible for rendering your templates.

The file to edit is src/Core/MultilingualRouter.php, inside the renderMultilingualTemplate method. Here, you can add logic to fetch data and add it to the $data array that gets passed to the template.

Example: Creating a "Team Members" Page

Let's say we want to display a list of team members on our /about page.

1. Add the logic to the router:


// In src/Core/MultilingualRouter.php, inside renderMultilingualTemplate()

// ... after the initial $data array is created ...

// --- ADD YOUR PAGE-SPECIFIC LOGIC HERE ---
if ($subpath === 'about') {
    $team = [
        ['name' => 'Alice', 'role' => 'Lead Developer'],
        ['name' => 'Bob', 'role' => 'Project Manager'],
    ];
    $data['team_members'] = $team; // Add it to the $data array
}

try {
    // ... rest of the render logic
}
        

2. Display the data in your Twig file (pages/en/about.twig):


Our Team

    Team information is not available.


Method 2: Creating Reusable Global Functions

For logic you want to reuse across many different pages (like a utility function), the best approach is to register it as a global Twig function.

The file to edit is src/Core/TemplateEngine.php, inside the addCustomFunctions method.

Example: Creating a Global `get_setting` Function

Let's create a function that can retrieve a setting from a global config array.

1. Define and register the function:


// In src/Core/TemplateEngine.php, inside addCustomFunctions()

// --- ADD YOUR NEW FUNCTION HERE ---
$this->twig->addFunction(new \Twig\TwigFunction('get_setting', function (string $key) {
    // In a real app, this might come from a database or a config file
    $site_settings = [
        'site_name' => 'STCMS Project',
        'contact_email' => 'contact@example.com',
    ];
    return $site_settings[$key] ?? 'Setting not found';
}));
        

2. Use the function in any Twig file:


<footer>
    © {{ "now"|date("Y") }} {{ get_setting('site_name') }}.
    Contact us at {{ get_setting('contact_email') }}.
</footer>