3

So I'm using cookies to determine what entries I want to display on some specific pages. I have a lot of different cookies which will change which entries I should be displaying. I currently have around 12 different cookies so would end up with over a thoasad different possiblities. Here is an example if a person has a both the below cookies, they should see entries from all of the below sets so I would need to either merge or join these if that specific cookie was found and the entries for that match were set.

{% if getCookie('cookie1') %}
{% set cookie1Entries = craft.categories.group('resource').slug('slug1') %}
{% set cookie1Entries2 = craft.categories.group('resource').slug('slug2') %}
{% set cookie1Entries3 = craft.categories.group('resource').slug('slug3') %}

{% set entriescookie1 = craft.entries({
    group: 'resource',
    relatedTo: [
        'and',
        { targetElement: cookie1Entries },
        { targetElement: cookie1Entries2 },
        { targetElement: cookie1Entries3 }
    ]
}).limit(3).find() %}
{% endif %}

{% if getCookie('cookie2') %}
{% set cookie2Entries = craft.categories.group('resource').slug('slug4') %}
{% set cookie2Entries2 = craft.categories.group('resource').slug('slug5') %}
{% set cookie2Entries3 = craft.categories.group('resource').slug('slug6') %}

{% set entriescookie2 = craft.entries({
    group: 'resource',
    relatedTo: [
        'and',
        { targetElement: cookie2Entries },
        { targetElement: cookie2Entries2 },
        { targetElement: cookie2Entries3 }
    ]
}).limit(3).find() %}
{% endif %}

What would be the best way to merge all of these at the end of checking for cookies, and also prevent from showing duplicate entries? Not sure how I would go about joining or merging these entries, as I would need to check if entriescookie1 or entriescookie2 was also set.

3

Use Craft's indexBy and index them by ID. If then you use Twig's merge function the duplicates will be removed and everything will be available in one array.

And may I suggest that if you're going to have a lot of logics in your templates, you'd better move this to a plugin and rewrite it in PHP. Templates should mostly be about templating, not about logics.

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.