I'm trying to assign a date to a variable, for the purpose of breaking up the layout. Perhaps there's a better way to do this, so feel free to recommend alternatives.
I have a model for news_items, with a date field called news_date. I want to go through each of the model entries and start a new section whenever a new year is encountered. My plan was pretty basic:
{% assign curYear = "" %}
{% for news in contents.news_items %}
{% assign prevYear = curYear %}
{% assign curYear = news.news_date.year %} <-- this does not work
{% if prevYear != curYear %}
<h1>Press Releases for {{ news.news_date | format_date: '%Y' }}</h1>
{% endif %}
<p>{{curYear}}</p> <-- this is always empty
<p>{{news.content}}</p>
{% endfor %}
I tried various other syntaxes, like Time.parseTime(news.news_date).year
, but it seems like you can't do arbitrary Ruby in Liquid. Is there some way to achieve what I want, here?
Thanks for your assistance!
Thanks to a helpful person on the google group, the capture
tag was pointed out to me, which captures things that would be otherwise output on the page into a variable:
Instead of this (or the various iterations I tried with assign
):
{% assign curYear = news.news_date.year %}
This works perfectly well, taking advantage of the format_date
filter:
{% capture curYear %} {{ news.news_date | format_date: '%Y' }} {% endcapture %}