1

Currently i am using this approach for linking to a entry(single page) of a structure, for example a cta button on the homepage which links to the contact page.

{% cache %}
    {% set single = craft.entries.id('14').first() %}
    {% if single %}
        <a class="button button--full t-spacing" href="{{ single.url }}">{{ "Neem contact op" | translate }}</a>
    {% endif %}
{% endcache %}

Or for example a "read more" button next to some results of some structure without a index. Because thats set in the structure "pages" as a entry type.

But i feel like this is somewhat hacky.. Of course you can link to a page like so:

{{ url('contact') }}"

or

href="{{ "contact"|translate }}

But url() doesn't translate and what if the slug is changed by a user of the CP. So what is the usual way to get around this, are there any best practises? So far i can only think of linking all the individual buttons/links to entry fields in the CP, which the user has to fill in.

4

You could write a Twig macro to get the localized URL from an entry ID. Import it from _layout.html for example.

{% macro urlFromId(entryId) %}
    {%- set entry = craft.entries.id(entryId).first() %}
    {{- entry ? entry.url -}}
{% endmacro %}

{% import _self as macros %}

Then use this more concise code everywhere in your templates.

<a class="button" href="{{ macros.urlFromId(14) }}">{{ "Neem contact op"|t }}</a>
|improve this answer|||||

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.