1

In my matrix field, I want to be able to upload my image, and then upload another asset (in this case it would be a document) so that that image I upload links to that document.

I have my Matrix field setup like so:

Image -> -Image -linkedDocument

How can I set up a conditional where only add in the tag if I add an asset there?

Here is my relevant code:

% elseif block.type == "image" %}

        {% set image = block.image.first() %}

        {% if image %}
            <a href="{{ image.linkedDocument }}"><img src="{{ image.getUrl('thumb') }}" width="{{ image.getWidth('thumb') }}" height="{{ image.getHeight('thumb') }}" alt="{{ image.title }}"></a>
            {% endif %}
        {% endif %}
3

If you have an image, you want to display it, and if there is also a linkedDocument, you want the image to link to that document. This should handle both cases, without too much code duplication.

{% if block.type == "image" %}

  {% set image = block.image.first %}

  {% if image %}
    {# set the imgTag, which we will display regardless #}
    {% set imgTag %}
      <img src="{{ image.getUrl('thumb') }}" width="{{ image.getWidth('thumb') }}"  height="{{ image.getHeight('thumb') }}" alt="{{ image.title }}"></a> alt="{{ image.title }}">
    {% endset %}

    {% set linkedDocument = block.linkedDocument.first %}

    {# we may or may not have a linkedDocument. Display the image in either case #}
    {% if linkedDocument %}
      <a href="{{ linkedDocument.url }}">{{imgTag}}</a>
    {% else %}
      {{imgTag}}
    {% endif %}
  {% endif %}

{% endif %}
1
  • This is just another reason why I love the Craft CMS community. Thanks so much Marion! – misteroptimist Dec 18 '14 at 21:51
2

Very close. It just looks like you are trying to reference the 'linkedDocument' through 'image' instead of through the block, and you are not retrieving the url.

{% if block.type == "image" %}

    {% set image = block.image.first %}
    {% set document = block.linkedDocument.first %}

    {% if image %}
        {% if document %}<a href="{{ document.url }}">{% endif %}<img src="{{ image.getUrl('thumb') }}" width="{{ image.getWidth('thumb') }}" height="{{ image.getHeight('thumb') }}" alt="{{ image.title }}">{% if document %}</a>{% endif %}
    {% endif %}

{% endif %}

Update: Added conditional for if document. Essentially the same answer as Marion's.

2
  • How do I handle the case if there is no linked document? I want to be able to put in images without linked doucments and images with linked documents. – misteroptimist Dec 18 '14 at 20:33
  • Ah, ok. I didn't get that part from your question. Looks like Marion has an answer for you. – Douglas McDonald Dec 18 '14 at 21:01

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.