{{craftSnippets}}
Home Articles Plugins Starter theme Components on Github Gists About
  • Home
  • Articles
  • Using attr() function to render HTML attributes in Craft CMS
Posted on Jun 12, 2019 by Piotr Pogorzelski

Using attr() function to render HTML attributes in Craft CMS

Craft CMS 3.2 introduces new Twig function - attr(). It can be used to render HTML attributes from arrays of data. Learn how to use it to make your templates cleaner and easier to maintain.
Table of contents:
  • Example use of attr()
  • Without attr()...
  • ...and with attr()
  • How does attr() function works?
  • Further reading

So, why should you use attr() to generate HTML attributes instead outputting them manually?

Example use of attr() #

I will demonstrate how usefull attr() function is by using an example - let's say we are outputting contents of complicated matrix field into template. Each matrix block has multiple fields that influence its appearance and behavior:

  • Block can be styled using multiple classes that are chosen by using options from dropdown and lightswitch fields.
  • Block can have multiple data attributes that are used by javascript. These attributes are also set by dropdown and lightswitch fields.
  • Block can have a background color and text color set by using color fields.
  • Block can have hidden attribute if specific lightswitch field is set to the proper value.
  • It has ID attribute based on its plain text field.

Without attr()... #

Here's how our Twig code would look like without using attr() function:

<div 
class="single-block {{block.widthClass}} {{block.colorClass}} {{block.isImportant ? 'important-block'}}" 
style="background-color: {{block.bgColor}}; color: {{block.textColor}}"
data-animation="{{block.animationType}}" 
data-something="{{block.somethingField ? 'something' : 'not-something'}}"
{{block.hidden ? 'hidden'}} 
id="{{block.titleField|kebab}}" 
>
{# contents of block #}
</div>

That's a bit messy. Multiple Twig variables squished in one place, mixed with quotation marks and pieces of text.

...and with attr() #

Now, let's refactor our code with attr() function. All data related to HTML attributes can be stored in Twig object:

{% set attributes = {
    class: [
        'single-block', 
        block.widthClass, 
        block.colorClass, 
        block.isImportant ? 'important-block',
    ],
    style: {
        'color': block.textColor,
        'background-color': block.bgColor,
    },
    hidden: block.hidden,
    data: {
        animation: block.animationType,
        something: block.somethingField ? 'something' : 'not-something'
    },
    id: block.titleField|kebab
} %}
<div{{attr(attributes)}}>
{# contents of block #}
</div>

Looks cleaner, doesn't it? This is example result - rendered HTML:

<div id="some-block" class="single-block full-width pretty-background important-block" style="color: #ff0000; background-color: #ffffff;" hidden data-animation="fade-in" data-something="not-something">
{# contents of block #}
</div>

If you want to play around with attr() and render such HTML attributes yourself, but without setting up any matrix fields, you can use this object simulating matrix block:

{% set block = {
    widthClass: 'full-width',
    colorClass: 'pretty-background',
    isImportant: true,
    textColor: '#ff0000',
    bgColor: '#ffffff',
    hidden: true,
    animationType: 'fade-in',
    somethingField: false,
    titleField: 'some block',
} %}

How does attr() function works? #

Let's summarize what attr() function does with data passed to it:

  • Contents of class array - strings representing single classes - get properly concated while keeping necessary whitespace between each class.
  • Object style consisting of CSS property-value pairs is transformed into proper style attribute.
  • Contents of data object are transformed into multiple data-attributes. In the case of multidimensional arrays in data object, an array is serialized so it can be later retrieved from single data-attribute by javascript.
  • Objects with a single boolean value, like hidden, are rendered as empty HTML attributes (without value) - if boolean value is true or are not rendered at all - if boolean value is false.
  • Rest of objects with string value are just rendered as corresponding HTML attributes - like id for example.

Further reading #

  • Github issue that made it all happen

If you want to get latest updates on Craft CMS tutorials and components, follow me on Twitter or subscribe to RSS feed.
Articles on blog:
  • Frontend testing for Craft CMS websites with Codeception and Cypress
  • Building reactive Craft Commerce product page with Sprig plugin
  • Dynamically generated PDF attachments for Freeform submissions
  • Using template hooks in Craft CMS
  • Alpine JS modal component for Craft CMS
  • Using template UI elements to extend Craft CMS control panel
  • Matrix within a Matrix - possible solutions for Craft CMS
  • Universal email template for Craft CMS
  • Creating attributes table from entry fields in Craft CMS
  • Namespacing forms in Craft CMS
  • Creating map-based navigation for Craft CMS
  • Placeholder image macro for Craft CMS
  • Building AJAX contact form with Craft CMS
  • Using incognito field plugin for Craft CMS
  • Email footer creator made with Craft CMS
  • Infinite scrolling and lazy loading with Craft CMS
  • Using Javascript in Twig templates with Craft CMS
  • Twig templating tips and tricks for Craft CMS
  • Basic SEO functionality for Craft CMS
  • Working with dates in Craft CMS templates
  • Working with SVG images in Craft CMS templates
  • Responsive and lazy-loaded youtube videos with Craft CMS
  • Debugging and inspecting Twig templates in Craft CMS
  • Creating article excerpts with Twig component in Craft CMS
  • Adding favicons to Craft CMS website
  • Truncating text with Twig macros in Craft CMS
  • Universal language switcher for Craft CMS
  • Read time macro for Craft CMS
  • Using attr() function to render HTML attributes in Craft CMS
  • Building dynamic, AJAX based pagination for Craft CMS
  • How to add Disqus comments to Craft CMS website
  • Ellipsis pagination component for Craft CMS
  • Converting email addresses into links using Twig macro
  • Breadcrumb created from URL for Craft CMS
  • Best developer-oriented Craft CMS plugins
  • Search autocomplete component for Craft CMS
  • RSS feed - template component for Craft CMS
  • Testing emails sent by Craft CMS using Mailtrap
  • Quick edit link - Twig component for Craft CMS
  • Filtering entries in control panel using Searchit plugin
  • Fetching routes into Twig templates in Craft CMS


Frontend testing for Craft CMS websites with Codeception and Cypress

Building reactive Craft Commerce product page with Sprig plugin

Dynamically generated PDF attachments for Freeform submissions

Using template hooks in Craft CMS

Alpine JS modal component for Craft CMS

Using template UI elements to extend Craft CMS control panel

Matrix within a Matrix - possible solutions for Craft CMS

Universal email template for Craft CMS

Copyright ©2023 Piotr Pogorzelski