# How to Render a State Abbreviation in Craft CMS?

Folks,

Is there a way to render a state abbreviation in a front end template on Craft CMS? Currently, I have a plain text field that has the full text of a state and I would like to render the standard two letter abbreviation.

Here is my current code:

{% if eventType.eventState | length %}{{ eventType.eventState }}{% endif %}


I would be open to changing the field type (or downloading a plugin) if that makes things easier but don't see an address field or something that on the surface would be conducive to easily filtering down to an abbreviation.

I don't think there's anything native (and haven't seen a plugin) that does this, but one way to do it is to create a macro where you add all the states and their abbreviations to a map. Something like this should work:

In a file called templates/_macros/helpers.html or the like (abbreviations map shortened in example; you can find a full list here, just need to convert it to Twig object syntax):

{% macro abbreviateState(stateName) %}{% spaceless %}

{% set abbreviations = {
'Alabama': 'AL',
'Arizona': 'AZ',
'Arkansas': 'AR',
'California': 'CA',
'Connecticut': 'CT',
...
} %}

{{ abbreviations[stateName|trim] ?? stateName }}

{% endspaceless %}{% endmacro %}


{# Import macro at the top of the template #}
{% import '_macros/helpers' as helpers %}

{% if eventType.eventState | length %}

{{ helpers.abbreviateState(eventType.eventState) }}

{% endif %}


Of course, this solution hinges on the state names being typed properly (exactly the same way as they appear in the macro); if somebody were to write "New york" and you've got "New York" in the macro, a proper abbreviation would not be found and the state name "New york" would simply render as-is.

To mitigate this, you might consider opting for a different input field type other than Plain Text, e.g. a Dropdown where you set up all the states as options.

If you're sticking with a Plain Text field, you could also circumvent the specific issue of capitalisation being off by making the state names in the macro map all lowercase, and applying the |lower filter to the state name when you try to pull the abbreviation:

{% set abbreviations = {
'alabama': 'AL',