Symfony 2 Twig |date() not working?

爷,独闯天下 提交于 2019-12-11 08:12:18

问题


i have a little problem and I really don't know why. I am printing a datetime variable in twig with |date() but it is allways printing the actual time.

for Debugging I put the following Code in my Template:

<pre>
{% debug entity.getCreatedAt|date("d.m.Y H:i:s") %}
{% debug entity.getCreatedAt|raw %}
{% debug entity.CreatedAt|raw %}
{% debug entity.CreatedAt|date("d.m.Y H:i:s") %}

My Variable is called CreatedAt so normally I should get the correct output with entity.CreatedAt|date("d.m.Y H:i:s"), right?

My Debug output is as follows:

string '16.01.2013 13:46:03' (length=19) //entity.getCreatedAt|date("d.m.Y H:i:s")

object(DateTime)[4611] //entity.getCreatedAt|raw
 public 'date' => string '2013-01-16 13:46:03' (length=19)
 public 'timezone_type' => int 3
 public 'timezone' => string 'Europe/Berlin' (length=13)

object(DateTime)[4938] //entity.CreatedAt|raw
 public 'date' => string '2013-02-20 21:46:53' (length=19)
 public 'timezone_type' => int 3
 public 'timezone' => string 'Europe/Berlin' (length=13)

string '20.02.2013 21:46:53' (length=19) //entity.CreatedAt|date("d.m.Y H:i:s")

I don't understand why it is NULL as soon as I call CreatedAt. And OUTSIDE of the debug tag it is ALLWAYS NULL, not depending on the writing.

In my Entity I've got:

private $CreatedAt;

public function setCreatedAt($createdAt)
{
    $this->CreatedAt = $createdAt;

    return $this;
}

public function getCreatedAt()
{
    return $this->CreatedAt;
}

And in the YML I've got:

CreatedAt:
  type: datetime
  nullable: true

Does anybody see a mistake?? I really don't find it, maybe it is a bug?

Thanks


回答1:


If you want to access your private variable $CreatedAt outside your entity class, you have to call the public getter method getCreatedAt() (that's what it's here for).

And in your twig template, when you call {% debug entity.CreatedAt|date("d.m.Y H:i:s") %}, since entity.CreatedAt is NULL, the returned string is based on a new date object:

If the value passed to the date filter is null, it will return the current date by default.

http://twig.sensiolabs.org/doc/filters/date.html

UPDATE:

As mentioned by @insertusernamehere, twig automatically calls the public getter.
But this behavior seems to happen only when using the delimiters {{ }} over {% %}.

http://twig.sensiolabs.org/doc/templates.html#synopsis




回答2:


In PHP member functions are case insensitive and class members are case sensitive. So getCreatedAt will work as good as getcreatedat but CreatedAt differs from createdat.

Here are some further informations about that: Why are functions and methods in PHP case-insensitive?.



来源:https://stackoverflow.com/questions/14989330/symfony-2-twig-date-not-working

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