如何在 Twig 模板中呈现 DateTime 对象 [英] How to render a DateTime object in a Twig template
问题描述
我的实体之一中的一个字段是日期时间"变量.
如何将此字段转换为字符串以在浏览器中呈现?
这是一个代码片段:
{% for game in games %}...<td>{{game.gameTeamIdOne.teamName}} </td><td>{{game.gameTeamIdTwo.teamName}} </td><td>{{game.gameDate}}</td></tr>{% 结束为 %}
这是我的实体类中的变量:
/*** @var 日期 $gameDate** @ORMColumn(name="GAME_DATE", type="datetime", nullable=true)*/私人 $gameDate;
这是我收到的错误消息:
<块引用>模板渲染过程中抛出异常(Catchable Fatal Error: Object of class DateTime could not be convert to string in ...appcachedev wig9bad58fd3bb1517632badf1fdc7fa4a8.php第 33 行")在第 10 行的BeerBundle:Games:gameTable.html.twig"中.
虽然你可以使用
{{ game.gameDate|date('Y-m-d') }}
方法,请记住,此版本不尊重用户区域设置,这对于仅由一个国籍的用户使用的站点应该不是问题.国际用户应该显示完全不同的游戏日期,比如扩展 DateTime
类,并添加一个 __toString()
方法来检查区域设置并采取相应的行动.>
编辑:
正如@Nic 在评论中指出的那样,如果您使用 国际扩展的 Twig,您将有一个 localizeddate
过滤器可用,它显示用户的语言环境中的日期.这样你就可以放弃我之前扩展 DateTime
的想法.
One of my fields in one of my entities is a "datetime" variable.
How can I convert this field into a string to render in a browser?
Here is a code snippet:
{% for game in games %}
...
<td> {{game.gameTeamIdOne.teamName}} </td>
<td> {{game.gameTeamIdTwo.teamName}} </td>
<td> {{game.gameDate}}</td>
</tr>
{% endfor %}
Here is the variable in my entity class:
/**
* @var date $gameDate
*
* @ORMColumn(name="GAME_DATE", type="datetime", nullable=true)
*/
private $gameDate;
And here is the error message I am getting:
An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class DateTime could not be converted to string in ...appcachedev wig9bad58fd3bb1517632badf1fdc7fa4a8.php line 33") in "BeerBundle:Games:gameTable.html.twig" at line 10.
Although you can use the
{{ game.gameDate|date('Y-m-d') }}
approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the DateTime
class, and adding a __toString()
method to it that checks the locale and acts accordingly.
Edit:
As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate
filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending DateTime
.
这篇关于如何在 Twig 模板中呈现 DateTime 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!