markup.classes

A Twig macro that acts as a helper for combining a styles object (a checkbox field in the CMS), classes (an array usually populated using conditionals in the template), and prependClasses (a string).

Example: markup.classes(styles, classes, "text-" ~ alignment)

{%- macro classes(styles, classes, prependClasses) -%}
    {%- if styles|length or classes|length or prependClasses -%}
        class="
            {% if prependClasses %}{{ prependClasses }}{% endif %}
            {{ styles|join(" ") }}
            {{ classes|join(" ") }}"
    {%- endif -%}
{%- endmacro -%}

{# Example #}
{% import _self as markup %}

{# _styles_ is a Craft checkbox field #}
{%- set styles = styles is defined ? styles : [] -%}

{# Classes other than the _Styles_ checkboxes in the CP #}
{%- set classes = classes is defined ? classes : [] -%}

<div
    {{ markup.classes(styles, classes, "section") }}
    {%- if "has-bg" in classes -%}
        style="
            {%- if backgroundColor -%}
                background-color: {{ backgroundColor }};
            {%- endif -%}
            {%- if backgroundImage|length -%}
                {%- set image = backgroundImage.first() -%}
                background-image: url({{ image.url }});
                {#- Size the image @ 50% if it looks like a retina image -#}
                {%- if '@2x' in image.filename and 'bg-cover' not in styles -%}
                    background-size: {{ image.width / 2 }}px {{ image.height / 2 }}px;
                {%- endif -%}
            {%- endif -%}
        "
    {%- endif -%}
>