Recipe - Address Format Lava Shortcode (w/ Postal Code Shortener)
Skill level: Intermediate
Organization: The Village Church
Requires Rock: 1.14.5
{# strip images & classes from the HTML but otherwise leave structure #}
The Why
This comes from a RocketChat thread about the best way to deal with formatting postal codes that could either be 5 digits or a longer format (43609-4100 vs 43609). This recipe shows a solution using a Lava Shortcode to format the address from either LocationId or GroupLocationId.
How This Works
Let's assume you have an address (the example given was "2 Hippo Way Toledo, OH 43609-4100"). The following code:
{[ address locationid:'1047' fields:'Street1,City,State,PostalCodeShortened' ]}
Will return 2 Hippo Way Toledo, OH 43609
The Shortcode
Fields:
- grouplocationid / locationid / locationguid: One of these is required.
- fields: Comma-separated list of fields. See Location model for available fields. *
- json: (optional) Return the data in a json instead of formatted text.
- * Note: PostalCodeShortened will only return the first 5 digits of a postal code.
The Code:
{% if grouplocationid != empty and grouplocationid != null %}
{% grouplocation where:'Id == {{ grouplocationid }}' securityenabled:'false' %}
{% assign locationid = grouplocation.LocationId %}
{% endgrouplocation %}
{% endif %}
{% if locationguid != empty and locationguid != null %}
{% location where:'Guid == {{ locationguid }}' securityenabled:'false' %}
{% endlocation %}
{% else %}
{% location where:'Id == {{ locationid }}' securityenabled:'false' %}
{% endlocation %}
{% endif %}
{% if json == 'true' %}
{% assign fields = fields | Split:',' %}
{% capture json -%}
{
{%- for field in fields -%}
{%- if field == "PostalCodeShortened" -%}
"PostalCodeShortened": {{ location.PostalCode | Split:'-' | First | ToJSON }}
{%- else -%}
{{ field | ToJSON }}: {{ location | Property:field | ToJSON }}
{%- endif -%}
{%- unless forloop.last -%},{%- endunless -%}
{%- endfor -%}
}
{%- endcapture -%}
{{ json | FromJSON | ToJSON }}
{% else %}
{% assign fields = fields | Default:'Street1,City,State,PostalCodeShortened' | Split:',' | Join:' + " " + ' %}
{% assign fields = fields | Replace:'City + " " + State','City + ", " + State' %}
{% assign fields = fields | Replace:'PostalCodeShortened','PostalCode.SubString(0,5)' %}
{% location where:'Id == {{ locationid }}' select:'new ({{ fields }} AS Formatted)' securityenabled:'false' %}
{{ location.Formatted }}
{% endlocation %}
{% endif %}