TransWikia.com

Use dropdown field to add a class to the body tag

Craft CMS Asked by Stig Melón-Bratvold on April 20, 2021

I have a website where I want to be able to use different background colors on different project pages.

The way I want to achieve this is by having a dropdown field in Craft to select from a set of values on each project page. I will then use that to set a class on the body tag so that I can style that accordingly with css.

I have created a dropdown field with the handle backgroundColor.
I have added the these options as values:

  • default
  • yellow
  • green
  • blue
  • purple

and here is the code in the template

{% if entry.backgroundColor.default %}
  {% set bodyClass = "page-project" %}
{% elseif entry.backgroundColor.yellow %}
  {% set bodyClass = "page-project bg-yellow" %}
{% elseif entry.backgroundColor.green %}
  {% set bodyClass = "page-project bg-green" %}
{% elseif entry.backgroundColor.blue %}
  {% set bodyClass = "page-project bg-blue" %}
{% elseif entry.backgroundColor.purple %}
  {% set bodyClass = "page-project bg-purple" %}
{% endif %}

This gives me and error saying that the property does not exist.
Does anyone know what the problem might be, or if there is a better way to do this.

Thanks!

2 Answers

Set up your dropdown so that the Option Labels are default, yellow, green, etc. and the Values are page-project, page-project bg-yellow, page-project bg-green, etc. Then, you can

{% set bodyClass = entry.backgroundColor %}

This will set bodyClass to whatever the value is for the chosen dropdown element, i.e. page-project if you pick the default option.

Answered by Marion Newlevant on April 20, 2021

I found the answer in this thread Dropdown field value getting outputted multiple times

The correct syntax to achieve what I am trying to do is:

{% if entry.backgroundColor.value == "default" %}
    {% set bodyClass = "page-project" %}
{% elseif entry.backgroundColor.value == "yellow" %}
    {% set bodyClass = "page-project bg-yellow" %}
{% elseif entry.backgroundColor.value == "green" %}
  {% set bodyClass = "page-project bg-green" %}
{% elseif entry.backgroundColor.value == "blue" %}
  {% set bodyClass = "page-project bg-blue" %}
{% elseif entry.backgroundColor.value == "purple" %}
  {% set bodyClass = "page-project bg-purple" %}
{% endif %}

Answered by Stig Melón-Bratvold on April 20, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP