Skip to content

Instantly share code, notes, and snippets.

@clineamb
Last active November 1, 2023 12:32
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clineamb/f64995df8b7ef006b094 to your computer and use it in GitHub Desktop.
Save clineamb/f64995df8b7ef006b094 to your computer and use it in GitHub Desktop.
Nunjucks Date/Time Field Macros
/*
* For use with the nunjucks templating system
* http://mozilla.github.io/nunjucks
*
* I created a bunch of macros for quickly creating date/time fields.
* Import into your nunjucks template:
* "{% import "path/to/datefields.nunjucks" as datefields %}"
* And use...
* {{ datefields.month_select("yo_month", "M", "", "form-control") }}
*
* See the code for usage examples.
*
* - Caroline, 9/23/2014
*/
{# month_select - create a select field with month options #}
{% macro month_select(fieldname, format="Month", _id="", _classes="") %}
{# format="Month / Mon / MON / MM (01, 02...) / M = "1, 2" #}
{% set
months_fullname = [
"January", "Feburary", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"
]
%}
{% set
months_short = [
"Jan", "Feb", "Mar",
"Apr", "May", "Jun", "Jul",
"Aug", "Sept", "Oct",
"Nov", "Dec"
]
%}
{% set
months_num = [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
]
%}
<select name="{{ fieldname }}" id="{{_id}}" class="{{_classes}}">
{% if format == "MON" %}
{% for mon in months_short %}
<option>{{ mon | upper}}</option>
{% endfor %}
{% elif format == "Mon" %}
{% for mon in months_short %}
<option>{{ mon }}</option>
{% endfor %}
{% elif format == "MM" %}
{% for mm in months_num %}
<option>{{ "0" if mm < 10 else "" }}{{mm}}</option>
{% endfor %}
{% elif format == "M" %}
{% for mm in months_num %}
<option>{{mm}}</option>
{% endfor %}
{% else %} {# "Month" #}
{% for month in months_fullname %}
<option>{{month}}</option>
{% endfor %}
{% endif %}
</select>
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment