3

I'm new to Craft CMS and can't figure out how to link images with the code below to its own page. Any suggestions?

{% for asset in entry.mainImages %}

    <a href="{# link to the image's page #}">
        <img src="{{ asset.url('thumb') }}">
    </a>

{% endfor %}

2 Answers 2

5

In Craft assets do not get "their own page" by default, but you can easily create them with a Dynamic Route. So go to Settings → Routes and add a new route with a number token, e.g. assets/<number> and route those URIs to a new template, e.g. assets/_entry.

With this route set up you can now link to an asset's entry page like so:

<a href="{{ url('assets/' ~ asset.id) }}">
    <img src="{{ asset.url('thumb') }}">
</a>

In your assets/_entry.html template you do now query for your asset via its ID, which is now available as a variable named "number". Use the exit tag to 404 the request in case no asset was found for the given ID.

{% set asset = craft.assets.id(number).first() %}

{% if not asset %}
    {% exit 404 %}
{% endif %}

<figure>
    <img src="{{ asset.url('fullscreen') }}">
    <figcaption>{{ asset.caption }}</figcaption>
</figure>
3

It's not clear what exactly you mean by 'its own page'

Do you want to have an entry for each image? or a twig template that displays that image?

When you access a page by default {{ entry.url }} refers to the entry of the page you are currently on.

You can link to the {{ asset.url }} but I'm not certain that is what you are trying to achieve.

Please update your question so we can help you further.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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