New Functions

If you need to build custom functions for your site, you can place them in the project-files/site-functions.php file.

Here is an example of a function along with how to use it in Twig:

// Generate a random number between two values.
// Add this function to Twig to be used on the front-end.
$Twig_generateRandomNumber =
    new \Twig\TwigFunction('generateRandomNumber', function ($a, $b) {
        return random_int($a, $b);
    });
$twig->addFunction($Twig_generateRandomNumber);

Using in Twig:


	<div class="container">
		<h1>Your random number is...</h1>
		<h2>{{ generateRandomNumber(1, 100) }}</h2>
	</div><!-- end container -->

Reusable HTML component example

Twig functions can come in handy for creating reusable components, because it keeps everything consistent and easy to make. Much like the form generator, you can create your own reusable pieces. This is an example of creating a common "back button" to put at the top of your pages, so the user can easily navigate back to where they came from without clicking the browser back button.

// Reusable component: Back button
	$Twig_backButton =
	new \Twig\TwigFunction('backButton', function ($text, $url) {
	return "
	<div class="mb-3">
		<a href='$url' class='btn btn-light'>⬅️&nbsp; $text</a>
	</div>
	";
	}, ['is_safe' => ['html']]);
	$twig->addFunction($Twig_backButton);

Using in Twig:


	<div class="container">
		{{ backButton("Documentation", "/documentation/") }}
		<h1>Your Cool Site Title Here</h1>
	</div><!-- end container -->

Turns into:


	<div class="container">
		<div class="mb-3">
			<a href="/documentation/" class="btn btn-light">⬅️&nbsp; Documentation</a>
		</div>
		<h1>Your Cool Site Title Here</h1>
	</div><!-- end container -->

The real usefulness comes from when you need to make a site-wide update. If your design changes to be a new back icon, it only takes one update to reflect across the entire site.