2

How do I filter a list of entries by the value of a field using the value of a variable?

e.g.

{% set location = block.locationVacancies %}
{% set entries = craft.entries.section('careers').search('locationVacancies:"{{location}}"')

doesn't work for me. But if I replace {{location}} with the value of the string location by hand then it works

{% set entries = craft.entries.section('careers').search('locationVacancies:"uk"')
2

Twig has an interpolation syntax (using #{} inside a double-quoted string) to accomplish this:

{% set location = block.locationVacancies %}
{% set entries = craft
    .entries
    .section('careers')
    .search("locationVacancies:#{location}")
    .all() %}

In addition, you can be more explicit about the values you’re searching for (and avoid any kind of sneaky search capabilities/side-effects exposed by using raw query input):

{% set location = block.locationVacancies %}
{% set entries = craft
    .entries
    .section('careers')
    .locationVacancies("*#{location}*")
    .all() %}

…or even using Twig object syntax…

{% set location = block.locationVacancies %}
{% set entries = craft.entries({
    section: 'careers',
    locationVacancies: "*#{location}*"
}).all() %}

(locationVacancies: location will also work, but disables partial matching)

It should be noted: if you're looking to associate multiple explicit entries, you can also make the field within your (presumed) Matrix Block an Entries field, which establishes actual relationships in the database—accessing such a field (myBlock.myLocationEntriesField.all()) will return that list of Entries, exactly as set in the admin) If you just need a dynamic search param, what you have is a fine solution!

1
{% set location = block.locationVacancies %}
{% set entries = craft
    .entries
    .section('careers')
    .search('locationVacancies:"' ~ location ~ '"')
    .find()
%}

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.