4

I'm trying to get the content of a single using a slug from the url. I'm using the following code:

{% set item = craft.entries.slug(craft.request.getSegment(1)).first() %}

This doesn't work, returns null, if there is a dash in segment 1.

For example if I have the following url: http://craft.dev/this-is-a-segment/segment2 And in craftcms I have a single with title "This is a segment" and url "this-is-a-segment" I can't get the content of that single.

If I change the slug to camelcase it does work, but I was under the impression that slug and section handle were two different things...

Is this a bug or am I doing something wrong?

1
  • 1
    your code above should work provided your slug is the same as the first segment. have you double checked? if yes, and you're on the latest version of craft, then i would report it as a bug.
    – Ben Croker
    Commented Dec 16, 2014 at 16:21

2 Answers 2

2

Singles have no need for slugs, which is why we don't expose them in the CP UI for a single.

They only have one in the database because they're technically entries, and entries need slugs. But it's only a concept meant for Channel and Structure entries.

2

I don't think that either the single's uri or the handle is technically considered a slug per se, although in the case of singles craft likely interprets the handle as such. A more appropriate way to access a single would be by using its section handle.

(updated)

{% if craft.request.getSegment(1) == "this-is-a-segment" %}
    {% set item = craft.entries.section('mySectionHandle').first() %}
{% endif %}
3
  • Your code won't work. In my example the slug returned from getSegment(1) is "this-is-a-segment". The section name however is thisIsASegment Commented Dec 16, 2014 at 16:44
  • ah... your right, of course it did. If you want to do this I would suggest making sure that the uri that you are using also matches the single's handle. Either that or use a conditional to use the correct handle. Commented Dec 16, 2014 at 16:48
  • That's what the craft.entries.section() function is for. I expected the craft.entries.slug() funtion to behave differently, which it does when using it to get the content of a channel or structure entry. Commented Dec 16, 2014 at 16:57

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.