1

I'm building my first Craft site and need to set a variable if a field has an image and then use that variable elsewhere in the template.

The field is part of a matrix and will repeat.

What I have so far is:

{# extra image #}
{% set asset = block.extraImage.first() %}
{# set variable empty so it's avialble outside of conditional #}
{% set float = "" %}

{% if asset %}
    <img src="{{ asset.url }}" alt="" class="img-responsive pull-right" />

    {% set float = yes %}           
{% endif %}

<div class="{{ float }}"> more code here </div>

The above code doesn't give me any template errors. But it also doesn't output the class as expected.

The full template code can be viewed here.

3

You're trying to your float variable using another variable at the moment that isn't defined. I expect you mean to set float to the string value "yes" like so:

{% set float = "yes" %}

You could also use a conditional around your class declaration so you don't end up with empty classes and it'd also remove the need to define float as an empty value.

<div{% if float is defined %} class="{{ float }}"{% endif %}> more code here </div>

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.