I'd like to use a single template to pull in entries from different channels based on url segment 2. But it seems I need to change the section attribute to match the url segment:

{% for entry in craft.entries.section('mySection').find() %}

Given that the url segment and section handle are different, can this be done?

For example the url segment might be hotel-california and the section handle of the section I want entries from could be hotelCalifornia or hotelsInCalifornia.


Personally, in situations like this (particularly if there's only a few items, and no easy way to automate it with inflection or similar,) I just use an array as a kind of dictionary.

{% set sectionHandlesBySegment = { 
    'hotel-california': 'hotelsCalifornia',
    'hotel-florida':    'hotelsFlorida' }

{% if not craft.request.getSegment(2) in sectionHandlesBySegment|keys %}
    {% exit 404 %}
{% endif %}

{% set sectionHandle = sectionHandlesBySegment[craft.request.getSegment(2)] %}
{% set hotels = craft.entries.section(sectionHandle) %}

You could use the "object syntax" of the ElementCriteriaModel, in combination with an if-statement:

// Checks if the 2. segment of the url is 'hotel-california'
{% if craft.request.getSegment(2) == 'hotel-california' %}
    {% set params = { section: 'hotelCalifornia' } %}
{% else %}
    {% set params = { section: 'anotherSection' } %}
{% endif %}

{% for entry in craft.entries(params) %}
    {{ entry.title }}
{% endif %}

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.