if i have a custom table (ct_table) and i have to use MySQLi commands on it using the PHP syntax, it won't work if i put the PHP snippets inside a twig file.

So are there any tools or official methods to convert PHP syntax DB-commands to TWIG syntax? or even let the Twig engine understand the PHP code?

1 Answer 1


You can't put PHP code into Twig, and there's no straightforward way to write custom DB queries in Twig. That's by design – Twig is a templating language, not meant for custom queries or processing.

Instead, you should provide a service object with utitily methods that you can call from Twig. Depending on your use-case, you can accept parameters (for example, arguments to a query) to get the flexibility you need.

First, look at the link above to learn more about services. If you're building a plugin, your service class goes in there. If you're working on some site-specific functionality, you can put it in a module instead. Once you have defined your service class and added it as a component to your plugin or module, you need to make it available to Twig – see the documentation on Extending Twig. For a plugin, extending the CraftVariable would be the most common way to provide a custom service object to Twig. In a module, I'd use a Twig extension instead, though that's mostly preference.

  • 1
    Thank you @MoritzLost it's all clear now, thanks to you.
    – Ra3d K
    Commented Nov 2, 2021 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.