The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Creating an Age Drop-down with Twig range()

by Ryan Irelan

Even though Twig is just (just) a templating engine for PHP applications (like the super smooth Craft CMS), it can also do lots of “programmy” things on its own, too.

Let’s say I need to create a form that includes a Age drop-down select field. I could populate the form element with data from a database or maybe some fancy library.

Or I could just build it in Twig. No outside data, like Craft data, is needed. Just Twig. All by itself.

Enough chit-chat, here’s the code:


<select name="age">
{% for age in range(1, 100) %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>

In this example we’re creating a select field element called age and outputting an option element with a bunch of ages. 1 to 100 to be precise.

We use the range function that comes with Twig. It’s really just a mirror of PHP’s range function. But we don’t have to write PHP!

The range function returns integers, in order, based on the range you specify.

range(1, 100)

The number to the left of the comma is the beginning of the range. The number to the right is the end of the range. Everything in between–and including–those numbers will be outputted.

When we iterate over a range with a for-loop, and include an option tag, we get a handy age menu.


{% for age in range(1, 100) %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}

We use the age variable to create a value for each option element, which we could then store when that option is selected.

When rendered, it looks like this:

Try it out in a Craft template to see it in action.

We can also use a shorthand version of the range function with the .. operator (in the docs they call it “syntactic sugar” mmmm). It’s a simpler way of writing the same thing:


<select name="age">
{% for age in 1..100 %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>

And that’s how you generate a data-filled age field with just Twig.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Filed Under: Craft CMS, Twig