Check if a variable is a date with Twig(检查变量是否是 Twig 的日期)
问题描述
我有一个变量数组,我想在 Twig 模板中显示,每个变量可以是字符串或日期.
I have an array of variables that I want to display in a Twig template and each variable can be either a string or a date.
如果变量是日期,我想像这样应用 date
过滤器:
If the variable is a date, I want to apply the date
filter like this:
{{ my_var|date('d/m/Y') }}
如果它是一个字符串,我希望它以通常的方式显示它:
And if it's a string I want it to display it the usual way:
{{ my_var }}
有什么方法可以测试变量是否为日期(即 PHP DateTime 对象的实例)?
Is there any way to test if a variable is a date (ie. an instance of the PHP DateTime object)?
推荐答案
也许不是最好的方法,但我找到了解决问题的方法.
Maybe not the best way to do it, but I found a solution to my problem.
{% if my_var.timestamp is defined %}
{{ my_var|date('m/d/Y') }}
{% else %}
{{ my_var }}
{% endif %}
作为 DateTime
PHP 对象有一个公共的 getTimestamp
方法,这是一种检查变量是否为日期的方法,无论该属性是否设置.
As a DateTime
PHP object has a public getTimestamp
method, it's a way to check if the variable is a date whether this property is set or not.
这篇关于检查变量是否是 Twig 的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:检查变量是否是 Twig 的日期


基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01