问题
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