skip to Main Content

I am using twig templates with wordpress and I am trying to output a date but when I try to format the date it formats correctly but it renders today’s date, not the date that I am trying to render.

{% for item in program_schedule %}
  {{ item.training_date_current }} // renders correctly 05/Aug/2021
  {{ post.published_at|date("d/M/Y") }} // renders 07/Jul/2021 - should be same as above
{% endfor %}

It is very strange, any idea why this is happening and how to fix?
Thank you.

2

Answers


  1. In php the date method has 2 arguments from which 1 is optional as mention in manual. The string format is required and the second argument being timestamp. If the timestamp is not provided then it takes the current timestamp and gives you today’s date (07/Aug/2021). It could be that you expected post.published_at|date("d/M/Y") to pass the published_at as second argument which wasn’t the case.

    You would want to call date method as date("d/M/Y", $dt) where $dt is the timestamp. One way of create timestamp is by using mktime(hour, minute, second, month, day, year)

    Login or Signup to reply.
  2. Because in a loop you set your singular post as item but applying published_at at post which in Timber may served from global context (basically it is current singular page). You may install Debug Timber Bar it will help you to find what in the context or check {{ dump(_context) }}. Change your loop to

    {% for item in program_schedule %}
      {{ item.training_date_current }}
      {{ item.published_at|date("d/M/Y") }}
    {% endfor %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search