The first two lines of code determine the start year and the current year.
The next block of code compares the two years, and sets the copyrightYears
variable accordingly.
Finally, we simply output copyrightYears
along with the rest of the copyright text.
{% set startYear = 2010 %}
{% set currentYear = now.year %}
{% if startYear == currentYear %}
{% set copyrightYears = startYear %}
{% else %}
{% set copyrightYears = startYear ~ ' - ' ~ currentYear %}
{% endif %}
<p>© {{ copyrightYears }} Site Name. All Rights Reserved</p>
You may want to quickly read about the native now
variable, a DateTime object which contains data about this exact moment in time (per your timezone).
It's also worth mentioning... There are a few shorter ways to do this, this example was written with the purpose of breaking down each step individually. If you'd like to trim this code down further, I'd suggest looking into one or both of these Twig capabilities:
Example of using a ternary statement:
{% set copyrightYears = ((startYear < currentYear) ? (startYear ~ ' - ' ~ currentYear) : startYear) %}
Example of using a macro:
<p>© {{ myMacroSet.myMacro(2010) }} Site Name. All Rights Reserved</p>
Of course, don't forget to import
"myMacroSet" before you call it!
$startYear - $currentYear
is going to be -5. So you'd get© -4 Sitename. All Rights Reserved"
$startYear - $currentYear
will be2010 - 2015
. There's no subtraction, it's just a string.