【问题标题】:Symfony 2 Twig |date() not working?Symfony 2 Twig |date() 不工作?
【发布时间】:2013-02-20 20:30:57
【问题描述】:

我有一个小问题,我真的不知道为什么。我正在使用 |date() 在树枝中打印日期时间变量,但它总是打印实际时间。

为了调试,我将以下代码放入我的模板中:

<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") %}

我的变量被称为 CreatedAt,所以通常我应该使用 entity.CreatedAt|date("d.m.Y H:i:s") 获得正确的输出,对吗?

我的调试输出如下:

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")

我不明白为什么我一调用 CreatedAt 就为 NULL。并且在调试标记之外它始终为 NULL,不取决于写作。

在我的实体中,我有:

private $CreatedAt;

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

    return $this;
}

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

在 YML 中我得到了:

CreatedAt:
  type: datetime
  nullable: true

有人看错了吗??实在是没找到,可能是bug吧?

谢谢

【问题讨论】:

  • 你使用{{ entity.CreatedAt|date("d.m.Y H:i:s") }}有同样的结果吗?
  • 我已经测试过了,真的无法重现...你使用dump而不是`{% debug %}得到相同的结果吗?
  • 你好 Cheesemacfly,我今天解决了我的问题 - 这是一个非常愚蠢的错误!我有一个名为 CreatedAt() 的 prePersist 类,Twig 当然在调用它 - 并收到 NULL .. 所以我将我的 prePersist 类重命名为 prePersist() 现在它工作得很好!

标签: symfony twig symfony-2.2


【解决方案1】:

如果你想在你的实体类之外访问你的private变量$CreatedAt,你必须调用publicgetter方法getCreatedAt()(这就是它的用途)。

在你的树枝模板中,当你调用{% debug entity.CreatedAt|date("d.m.Y H:i:s") %}时,由于entity.CreatedAtNULL,返回的字符串是基于一个新的日期对象:

如果传递给日期过滤器的值为空,则默认返回当前日期。

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

更新:

正如@insertusernamehere 所述,twig 会自动调用公共 getter。
但是这种行为似乎只有在使用分隔符 {{ }} 而不是 {% %} 时才会发生。

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

【讨论】:

  • 其实Twig会为你调用getter方法。
  • 感谢您的回答,我也尝试使用 public $createdAt,但它不会改变这种行为。我认为最有趣的是在 {% debug entity.getcreatedat|date("d.m.Y H:i:s") %} 我得到了正确的结果,但是没有调试我得到 NULL ......这就是我真正的不明白
  • @insertusernamehere 起初我同意你的观点,但你确定当对象在{% %}而不是{{ }}之间访问时是这种情况吗?
  • 看来你是对的。将 public 添加到 CreatedAt 并使用 entity.CreatedAt|date("d.m.Y H:i:s") 打印它,它现在正在工作。但例如,我也得到了一个字符串“private $PersonGender;”而这一个也在私人模式下打印,只有我需要公众的日期时间。也许是因为它需要对公共方法做一些 ->format() 工作?
  • 如果你使用{{ entity.CreatedAt|date("d.m.Y H:i:s") }}你不会得到预期的结果吗?
【解决方案2】:

在 PHP 中,成员函数不区分大小写,而类成员区分大小写。所以getCreatedAt 将与getcreatedat 一样好,但CreatedAtcreatedat 不同。

以下是有关此的更多信息:Why are functions and methods in PHP case-insensitive?

【讨论】:

  • 您好 insertusernamehere,是的,我知道区分大小写,这样做只是为了显示我的错误。请看一下上面的例子,我会在一秒钟内更新它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-16
  • 1970-01-01
  • 2015-03-31
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多