如何在Twig模板中呈现DateTime对象 [英] How to render a DateTime object in a Twig template
问题描述
我的一个实体中的一个字段是一个datetime变量。
如何将该字段转换为一个字符串以在浏览器中呈现? / p>
这是一个代码片段:
{%游戏中的游戏%}
...
< td> {{game.gameTeamIdOne.teamName}}< / td>
< td> {{game.gameTeamIdTwo.teamName}}< / td>
< td> {{game.gameDate}}< / td>
< / tr>
{%endfor%}
这是我的实体类中的变量:
/ **
* @var date $ gameDate
*
* @ ORM\Column name =GAME_DATE,type =datetime,nullable = true)
* /
private $ gameDate;
这里是我收到的错误消息:
渲染模板时抛出异常(Catchable致命错误:DateTime类的对象无法转换为... \app\cache\中的字符串第10行中的BeerBundle:Games:gameTable.html.twig中的dev \twig\9b\ad\58fd3bb1517632badf1fdc7fa4a8.php line 33)
虽然可以使用
{{game .gameDate | date('Ym-d')}}
方法,请记住,这个版本不尊重用户区域设置,这不应该是仅一个国籍的用户使用的站点的问题。国际用户应该显示游戏日期完全不一样,例如扩展 \DateTime
类,并添加一个 __ toString()
修改:
如@Nic在评论中所指出的那样,如果您使用 Twig的Intl扩展版,您将有一个 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
*
* @ORM\Column(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 ...\app\cache\dev\twig\9b\ad\58fd3bb1517632badf1fdc7fa4a8.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屋!