Wednesday, 21 October 2020

Render a DateTime object in Twig

PHP  Twig 

The date filter

In Twig, the date filter uses the same DateTime format of PHP to render DateTime instances in server-side.

require_once './vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('./themes');

$twig = new \Twig\Environment($loader);

$twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone('Australia/Melbourne');

$dt = new DateTime("2010-07-05 06:00:00", new DateTimeZone("Australia/Melbourne"));

echo $twig->render('render-a-datetime.twig', array("myDateTime" => $dt));

In the above PHP code snippet, the function setTimezone is used to set the default timezone globally in Twig. In line 9, the new DateTime instance $dt is created with the timezone of Australia/Melbourne. After that, it is passed to the template file render-a-datetime.twig. In the template file, we can render the DateTime variable myDateTime like this:

{{ myDateTime|date("d M Y H:i") }}

The output will be:

05 Jul 2010 06:00


If want to show the current date in Twig, we can use the word now.

{{ "now"|date("d M Y H:i") }}

The date filter with a timezone

We can override the default timezone in the date filter with a given timezone string. For the details of the supported timezones, you can refer to List of Supported Timezones. For example, you can display the current date instance for different cities.

<p>
   New York: {{ "now"|date("d M Y H:i", "America/New_York") }} <br>
   Paris: {{ "now"|date("d M Y H:i", "Europe/Paris") }} <br>
   Hong Kong: {{ "now"|date("d M Y H:i", "Asia/Hong_Kong") }} <br>
   Melbourne: {{ "now"|date("d M Y H:i", "Australia/Melbourne") }}
</p>

The above code will output:

New York: 20 Oct 2020 20:30
Paris: 21 Oct 2020 02:30
Hong Kong: 21 Oct 2020 08:30
Melbourne: 21 Oct 2020 11:30

Related posts

Setup Twig for the web project in WampServer on Windows



Search