Skip to main content

twig_query

Period
2022 – 2024
Kind
Drupal module
Status
archived
License
Open Source
Website
www.drupal.org/project/twig_query

CraftCMS has one of the nicest template APIs I know — Element Queries: fluent content lookup straight from Twig, no detour through a controller or preprocess hook.

Drupal didn't have anything like it. So I built twig_query at Roromedia — as a standalone open-source module on Drupal.org, presented at DrupalCon Prague 2022.

An example — find related projects sharing tags with the current node, excluding the node itself:

{% set projects = query.entries
    .type('project')
    .where(['field_tags', node.field_tags|map(term => term.entity.tid.0.value), 'IN'])
    .where(['nid', node.nid.0.value, '!='])
    .orderBy('created ASC')
    .limit(3)
    .all() %}

{% for project in projects %}{{ project.title.0.value }}{% endfor %}

Fully unit-tested, compatible up to Drupal 11.

The Drupal world traditionally leans on render arrays for content composition — the fluent-query approach never gained traction. I'm no longer actively maintaining the module; Drupal isn't a focus for me anymore.