3

Basically I want to add certain parameters to my 'craft.entries' based on whether a variable is set:

{# Get a start date value from the URL (my use case) #}
{% set start_date = craft.request.getSegment(3) %} {# e.g. '2015-12-10' #}

{% if start_date != "" %}

  {# Create .after() param #}
    {% set startDateQuery = ".after(" ~ start_date ~ ")" %}

{% else %}

    {# If there is no start date then set the param as "" so nothing happens #}
    {% set startDateQuery = "" %}

{% endif %}

{% set entries = craft.entries.section('events') ~ startDateQuery %}

{% paginate entries as pageInfo, pageEntries %}
  ... Do stuff

I've tried this other ways as well, but this one seemed the most appropriate. Either way, it's not working and I was wondering if anyone might know why - or have a suggestion of a better method?

Cheers!

4

Instead of using the chained syntax, you should build a parameter object and pass that in to craft.entries, like so:

{# Get a start date value from the URL (my use case) #}
{% set start_date = craft.request.getSegment(3) %} {# e.g. '2015-12-10' #}

{# Create a parameter object, with default values #}
{% set params = { section: 'events' } %}

{# If start_date exists, add the after parameter to the object #}
{% if start_date != "" %}
    {% set params = params | merge({ after: start_date }) %}
{% endif %}

{# Get the entries by passing the parameters to craft.entries() #}
{% set entries = craft.entries(params) %}
| improve this answer | |
  • Absolutely perfect! I figured this would be the best way to it, but I've not seen it done this way before so I wasn't sure where to start. Cheers mate! – Lighty_46 Dec 22 '15 at 14:58

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.