6

I've been struggling all evening with getting the urls of my singles in a menu generator. At first I thought I nailed it, but it turned out it used the title of the singles instead of the url. When I tried to get the url I an error, so clearly I'm doing something wrong.

This is the code to generate the menu:

{# generating menu #}
<nav class="nav">
    <ul class="hidden">
        {# Get all Sections #}
        {% set sections = craft.sections.getAllSections() %}

        {# Loop through all single sections #}
        {% for singleSection in sections if singleSection.type == 'single' %}

            {# Output #}
            <li class="">
                <a href="{{ singleSection.url }}">
                    <div class="link">{{ singleSection }}</div>
                </a>
            </li>

        {% endfor %}
    </ul>
</nav>

It is the singleSection.url that causes the error.

Craft\SectionModel and its behaviors do not have a method or closure named “url”.

I presume the SectionModel does not have an Url, but that doesn't bring me any close to solving my problem of getting the url of single pages.

3
  • Can you update the original question with the error that it's giving you?
    – Brad Bell
    Commented Jan 18, 2015 at 0:56
  • @BradBell probably it's: Craft\SectionModel and its behaviors do not have a method or closure named "url". Commented Jan 18, 2015 at 6:31
  • @BradBell, I updated the question. Commented Jan 18, 2015 at 10:12

3 Answers 3

8

Craft creates an EntryModel for each Single Section, that allows you to access the URL property you are after. You can get the (one) EntryModel using the Section's ID and the first() method:

{% set singleSectionEntry = craft.entries.sectionId(singleSection.id).first() %}

<a href="{{ singleSectionEntry.url }}">
    <div class="link">{{ singleSectionEntry.title }}</div>
</a>
2

To get an URL to a specific CraftCMS single entry. Look up for the entry unique id in admin panel and then apply in Twig template: Example below:

   {% set page_cookies_policy = craft.entries.id(10).first() %}
   {% set page_terms = craft.entries.id(11).first() %}

   <ul class="footer-sub-nav">
       <li>{{ page_cookies_policy.getLink() }}</li>
       <li>{{ page_terms.getLink() }}</li>
   </ul>
1
  • 3
    More readable in the code would be to use the following: {% set page_cookies_policy = craft.entries.section('cookie-policy-single-handle').first() %}
    – mrsmn
    Commented Sep 18, 2017 at 6:55
2

An other solution, you can use:

{{craft.entries.section("yourHandleSectionName").one().url}}

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.