Twig date filter not working with DateTime object

谁说我不能喝 提交于 2020-01-15 12:45:12

问题


I'm using CI2 with Doctrine2 and Twig for the template engine. I'm trying to display the date from an entity as a string, however it's not working for me.

I'm sending an array of Entity objects to the template, iterating through them, and displaying their properties:

{% for e in entities %}
    <span><label>username</label>{{e.getUserName}}</span>
    <span><label>email</label>{{e.getEmail}}</span>
    <span><label>date created</label>{{e.getCreatedAt | date('d.M.Y H:i:s')}}</span>
{% endfor %}

The getCreatedAt() method returns a DateTime object. I can use this object just fine from within PHP:

echo $e->getCreatedAt->format('YmdHis');

However from within Twig I can't seem to find any way to get a string printed. When I try the above way (which I've read is the correct way to do it) I get:

date() expects parameter 1 to be string, object given

I've tried several other methods:

{{e.getCreatedAt.format('d.M.Y H:i:s')}}
{{e.getCreatedAt}}
{{e.getCreatedAt | date('d.M.Y H:i:s') |strtotime}}

Nothing works out.

I was sure to add the 'date' Twig filter using the addFilter() method:

$this->twig->addFilter('date', Twig_Filter_Function('date'));

Any ideas what's going on?


回答1:


date is a built-in filter, you need not register it, especially not to the php date function, which cannot handle DateTime objects.



来源:https://stackoverflow.com/questions/10792246/twig-date-filter-not-working-with-datetime-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!