With the Scriban syntax being new to the Sitecore platform with v9.3 there is definitely a learning curve but well worth the time investment. So we will post short tips on things that we struggled with. This is to share but also I will have a place to find it again when I need it.
So you've created a date field in your Sitecore template and now need to format it for display purposes. Or even better, you have styling differences depending on if the dates and years match for start and end points. Let's show this below.
First, get the date(s) in your Scriban template from the item. In this scenario I was looping through child objects called i_child. Using the Scriban date.parse function I can get the date value from the Sitecore field by this:
{{
this.startDate = sc_field i_child 'Event Start' | date.parse;
this.endDate = sc_field i_child 'Event End' | date.parse;
}}
Now that we have the date values you can do things to check against the dates. If the start date and end date are not equal then display them both. If the start year and end year do not match then show both years. See the code below to show the three different display modes.
{{ if ( this.startDate.date != this.endDate.date ) }}
{{ if ( this.startDate.date.year != this.endDate.date.year ) }}
{{ this.startDate | date.to_string '%b %d, %Y' }} - {{ this.endDate | date.to_string '%b %d, %Y' }}
{{ else }}
{{ this.startDate | date.to_string '%b %d' }} - {{ this.endDate | date.to_string '%b %d, %Y' }}
{{ end }}
{{ else }}
{{ this.startDate | date.to_string '%b %d, %Y' }}
{{ end }}
Refer to the Scriban date formatting details here for further details. But this allows you get a date field from Sitecore and display the date format as you choose.
Until next time.
Comments
Post a Comment