4

This is a beginner question:

How do I create a link to an entry using entry's id?

I tried several combinations, such as {{ entry.getUrl(my_id) }}, {{ entry.url.id(my_id) }}, etc. but failed to found the correct syntax.

4

The reason why your example fail is that you are using the entry variable. You are trying to call the function getUrl on the model entry, but the function (or model) doesn't exist yet, and has to be created (fetched).

Example:

You can use craft.entries to fetch the EntryModel, and than output its url:

{% set my_id = 5 %}
{% set entry = craft.entries.id(my_id).first() %}
{{ entry.url }}

If you are in an entry loop, it works the same way:

{% for entry in craft.entries.section('blog') %}
    {{ entry.url }}
{% endfor %}
  • Thanks! I tried to add this link but all I got is a PHP error: CException — Craft\ElementCriteriaModel and its behaviors do not have a method or closure named "url". Same problem after chaining the 'entry' and 'my_id'. Any idea? – Romain Poirier Jul 6 '14 at 12:21
  • 2
    @Romainpoirier Just added .first() to the 2nd line of the first code block. That should fix your error. – Brandon Kelly Jul 6 '14 at 13:22
2

As a shorthand, you could also use Reference Tags along with the parseRefs filter, like this:

<a href="{{ '{entry:123:url}' | parseRefs }}">{{ '{entry:123:title}' | parseRefs }}</a>

(Performance-wise, I'm not actually sure how this compares to spinning up the ElementCriteriaModel. It wouldn't surprise me if Craft caches entry data it queries, so it's not running a separate query for each reference tag... but I'm not sure about that.)

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.