Sajith Rahim | Almanac | Blog
 
Dev

Class Template Directive in Astro

Sajith AR
Class Template Directive in Astro :
Dynamic classes in Astro JS.

Astro directives and syntax might change as the framework is actively being developed. Please check the official docs incase you encounter errors.
docs.astro →

Astro is an open-source front-end framework that leverages modern web standards for fast, optimized, and maintainable website development. It separates content from presentation, enhancing SEO and accessibility, while allowing integration of popular libraries such as React, Vue, Svelte, or HTML/CSS.

As I refactor code into reusable components often I run into a case where I prefer to have property driven styling for the component.

Astro has a built-in directive (class:list) meant for taking in arrays, sets, objects, strings, and more. Whatever array you pass in is flattened and added in the class attribute.

Syntax

Astro’s class:list={…} template directive “takes an array of class values and converts them into a class string.”

class:list takes an array of several different possible value kinds:

  • string: Added to the element class
  • Object: All truthy keys are added to the element class
  • Array: flattened
  • falsenull, or undefined: skipped

Any duplicate values are removed automatically.

Example

	
        
    
        
    
    
<!-- this 👇🏽 -->

<div
  class:list={[
     "wrapper",
     { "info-wrapper": isInfo,
         "alert-wrapper": !isInfo 
      }
  ]}
>
...
</div>

<!-- rendered as 👇🏽 for isInfo = true-->

<div class="wrapper info-wrapper">
...
</div>

Reference:  Astro Template Directives Documentation


CONNECT

 
Have something to share,
Let's Connect