Text Templates in PHP

PHP provides built-in support for creating dynamic content or showing customized output to the user with its templating capabilities. While PHP doesn’t have a separate template package like Go, it offers similar functionality through its string manipulation and output functions.

<?php

// We can create a simple template as a string with placeholders.
// In PHP, we typically use curly braces {} for variable interpolation.
$t1 = "Value is {value}\n";

// A function to render our simple template
function renderTemplate($template, $value) {
    return str_replace('{value}', $value, $template);
}

// "Executing" the template by replacing the placeholder
echo renderTemplate($t1, "some text");
echo renderTemplate($t1, 5);
echo renderTemplate($t1, implode(', ', ['PHP', 'Python', 'JavaScript', 'Ruby']));

// For more complex templates, we can use a heredoc syntax
$t2 = <<<EOT
Name: {name}
EOT;

// Rendering with an associative array (similar to a struct or map in Go)
$data = ['name' => 'Jane Doe'];
echo str_replace('{name}', $data['name'], $t2) . "\n";

// Another way to render with an associative array
$data = ['name' => 'Mickey Mouse'];
echo strtr($t2, $data) . "\n";

// Conditional rendering
function conditionalTemplate($condition) {
    return $condition ? "yes\n" : "no\n";
}

echo conditionalTemplate("not empty");
echo conditionalTemplate("");

// Looping through an array
$languages = ['PHP', 'Python', 'JavaScript', 'Ruby'];
echo "Range: " . implode(' ', $languages) . "\n";

// For more advanced templating, PHP developers often use template engines
// like Twig or Blade, which provide more powerful features similar to
// Go's text/template package.

To run the program, save it as templates.php and use the PHP CLI:

$ php templates.php
Value is some text
Value is 5
Value is PHP, Python, JavaScript, Ruby
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: PHP Python JavaScript Ruby

In this PHP version:

  1. We create simple templates as strings with placeholders.
  2. We use string replacement functions like str_replace() and strtr() to render templates.
  3. Conditional logic is implemented using a separate function.
  4. Looping is done using PHP’s built-in array functions.
  5. For more complex templating needs, PHP developers often use third-party template engines that provide more advanced features.

While PHP doesn’t have a built-in template package as sophisticated as Go’s text/template, it offers flexible string manipulation that can be used for simple templating. For more complex use cases, PHP developers typically turn to dedicated template engines that provide similar functionality to Go’s templating system.