2

I have created a plain text field that is assigned to a section and is available in the tabs for entries in that section. I want to use this field's value to modify the CSS on my template. My _entry.html file looks like the following:

{% extends "_layouts/site" %}
{% set title = entry.title %}
{% set modifierClass = entry.shortName %}
{% set bodyClass = "work modifierClass" %}

{% block main %}
<section class="entry is-centered cf">
  <article>
  </article>
</section>
{% endblock %}

I have assigned the entry.shortName to the customClass variable, but it is not working correctly. The text "modifierClass" is outputted in the body tag instead of what is entered in the entry.shortName field. If I place the {{ entry.shortName }} within the <article> tags, it is outputted correctly there.

Any reason why this is not working? Or am I not understanding how field values can be assigned to variables.

Cheers,

3

You've assigned the string 'work modifierClass' to the bodyClass variable, rather than adding the value of the modifierClass variable to bodyClass.

You can assign the value of modifierClass to bodyClass like this:

{% set bodyClass = 'work ' ~ modifierClass %}

The ~ (tilde) character is Twig's string concatenation operator.

You could even remove the modifierClass variable altogether and just do this:

{% set bodyClass = 'work ' ~ entry.shortName %}
1
  • Thanks for the solution. I am newish to Craft and was unaware of the concatenation operator in Twig. I have dumped the variable and placed the entry field in the bodyClass variable. Dec 1 '18 at 20:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.