How-to library · Developer docs

How-to library

Task-shaped pages: a title that starts with a verb, the situation in a few lines, the steps, the working code in both engines, and why this way rather than another. Found from a search, done, and left.

Convert component attributes into CSS classes

Selects and multiselects whose keys are classes, and switches named after the class they turn on, become one class string through a shared helper, so no component carries the loop. Include it in Smarty, import it in Twig.

Context

Context. Most attributes exist to become classes: sectionStyle, contentWidth, textAlign, a reverse switch. The helper takes a list of always-on classes, the attribute names whose text or values are classes, and the switch names, and returns one string. It relies on two conventions: option keys are the class names, and a switch attribute is named after the class it turns on. The full helper is on the patterns page; this is how a component uses it.

Steps

  1. Copy the helper into templates/includes/elements/attributes-to-css.html (Smarty) or templates/macros/css.twig (Twig) from the patterns page.
  2. In a component, call it with the base classes, the attribute names and the switch names.
  3. Print the result into the element's class attribute.
  4. Name new attribute options and switches to fit: component--wide as a key, columns--reverse as a switch name.

Template code

Template code
{include 'includes/elements/attributes-to-css.html'
  classes=['card', 'component']
  attributes=['sectionStyle', 'contentWidth', 'textAlign']
  flags=['card--reverse']}
<article class="{$classes}">
  {$component->body}
</article>
{% import 'macros/css.twig' as css %}
<article class="{{ css.classes(component, ['card', 'component'], ['sectionStyle', 'contentWidth', 'textAlign'], ['card--reverse']) }}">
  {{ component.body }}
</article>
Template code Smarty only
{* without the helper, for one attribute and one switch *}
<article class="card {$component->getAreaText('sectionStyle')}{if $component->getAreaText('reverse') == '1'} card--reverse{/if}">

Why this and not that

Not the shorthand ($component->sectionStyle) in a class attribute: in live preview it carries markup and breaks the tag. Not a mapping table from option keys to classes in the template: it drifts from the input type; make the keys the classes and there is nothing to map. Not a switch tested with !empty(): an off switch stores '0', which is not empty; compare with '1'.

Go deeper

Was this page helpful?

Your answer goes to the docs team.